Reputation: 11
I want to sort the "mystruct" by the distance variable, what is the fastest way of doing this?
struct MyStruct {
int scale;
bool pass;
float distance;
};
vector<MyStruct> mystruct;
...
sort (mystruct.begin(), mystruct.begin() + mystruct.size());
//this doesn't work since is trying to sort by "MyStruct" and not by a number
if I had a
vector<float> myfloat;
...
sort (myfloat.begin(), myfloat.begin() + myfloat.size());
then will work perfectly.
Upvotes: 1
Views: 1603
Reputation: 12277
You need to provide either a functor to the sort function, or a less than operator:
struct MyStruct_Compare {
bool operator()(const MyStruct& a, const MyStruct& b) {
return a.distance < b.distance;
}
}
std::sort(mystruct.begin(), mystruct.end(), MyStruct_Compare());
OR:
bool operator<(const MyStruct& a, const MyStruct& b) {
return a.distance < b.distance;
}
std::sort(mystruct.begin(), mystruct.end());
Upvotes: 5
Reputation: 38163
You need to write your own operator<
for your struct.
It should be something like
bool operator<( const MyStruct& s1, const MyStruct& s2 )
{
// compare them somehow and return true, if s1 is less than s2
// for your case, as far as I understand, you could write
// return ( s1.distance < s2.distance );
}
The other option is to write a functional object, but it's not that necessary here, writing operator<
is easier (for beginners)
Upvotes: 5