Saturday, January 12, 2013

Sort an Array of Structure in C++

Sample Code's start


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

struct sust
{
    int x , y;
};
sust array[100];


bool comp(sust x , sust y)
{
    if(x.x == y.x)
    {
        return x.y > y.y;
    }
    return x.x < y.x;
}

int main()
{
    int n = 10;
    for(int i = 0; i < 10; ++i)
    {
        array[i].x = 10;
        array[i].y = i+10;
    }

    sort(array, array+n, comp);

    for(int i = 0; i < 10; ++i)
    {
        cout << array[i].x << " " << array[i].y << endl;
    }

    return 0;
}

Sample Code's End


This sample code sort an array of structure according some condition in comp function where we see we write code for sort the structure variable in array ascending order of x values when x is same then you must sort in descending order.

No comments:

Post a Comment