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 fol开发者_如何学Clows:
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 use compare2
. (For case (3) you would have to write another predicate, or just use std::pair<int,int>
.)
Case 4: If you want the values of a
and b
sorted separately and destroy the pairing, then you need to put the values into separate vectors of ints and sort those individually:
std::vector<int> avals(array.size()), bvals(array.size());
for (size_t i = 0; i != array.size(); ++i)
{
avals[i] = array[i].a;
bvals[i] = array[i].b;
}
std::sort(avals.begin(), avals.end());
std::sort(bvals.begin(), bvals.end());
There is no way around this. A container of Entry
objects can only move elements around as a whole.
I think you are confusing what sort
does. It does not hort the members that you use in the comparison function, but rather the whole objects. In your case that means that the because you initialized one object with value pair (5,8)
, there will always be an element in the vector that is (5,8)
.
Sorting the array by the first member means that it move to the second to last position (5
being the second to last biggest first element), and sorting by the second element will move the object to, well in this case also the second to last position, but that will only move the object in the container, it will always be (5,8)
.
If you want both to impact the comparison, include both in the check (i.e. compare
) function. Else, it's either one or the other. If you need to have different "views", you need a smarter container (such as boost::multi_index)
精彩评论