I have a simple C++ code written to understand sort function usage on user defined class data types to sort data members of a class.
But this only sorts array of variable b in the class. Because, the earlier sorted array of variable a, is also disturbed whiel sorting b.
#include <iostream>
#include <cstring>
using namespace std;
class Entry
{
public:
int a, b;
};
bool compare1(Entry e1, Entry e2)
{
if (e1. a > e2. a) return false;
return true;
}
bool compare2( Entry e1, Entry e2)
{
if (e1. b > e2. b) return false;
return true;
}
int main()
{
int i;
vector<Entry> array(4);
array[0]. a =5 , array[0]. b =8 ;
array[1]. a =10 , array[1]. b =4 ;
array[2]. a =3 , array[2]. b =2 ;
array[3]. a =1 , array[3]. b =12 ;
sort(array.begin(), array.end(), compare1);
sort(array.begin(), array.end(), compare2);
cout << "sorted:" << endl;
for (i = 0; i< 4; i++)
cout << array[i]. a << " " << array[i].b << endl;
}
The output I get is as follows:
sorted:
3 2
10 4
5 8
1 12
How to sort both data member arrays – a,b?
It depends on how you want your elements to be sorted:
Sort as pairs, keyed on
a: (1,12), (3,2), (5,8), (10,4)Sort as pairs, keyed on
b: (3,2), (10,4), …Sort as pairs lexicographically: same as sorting on
a, since there are no repeated values fora.In case (1) you use
compare1, in case (2) you usecompare2. (For case (3) you would have to write another predicate, or just usestd::pair<int,int>.)Case 4: If you want the values of
aandbsorted separately and destroy the pairing, then you need to put the values into separate vectors of ints and sort those individually:There is no way around this. A container of
Entryobjects can only move elements around as a whole.