1

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.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
  • 1
    Define a comparator function, and then use `std::sort`. See the example e.g. here: http://cplusplus.com/reference/algorithm/sort/. – Oliver Charlesworth Jul 07 '12 at 14:03
  • Possible duplicate http://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects – jogojapan Jul 07 '12 at 15:17
  • possible duplicate of [Sorting a vector of objects by a property of the object](http://stackoverflow.com/questions/5174115/sorting-a-vector-of-objects-by-a-property-of-the-object) – ildjarn Jul 07 '12 at 15:39

2 Answers2

6

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)

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
  • 5
    This works, clearly. However, I would advise that one hesitates before using `operator<`, unless it clearly makes sense to say that one `MyStruct` is "less than" another. If it doesn't make sense, then it's probably clearer to use a named comparator function. I think this may be the case in the OP's example. – Oliver Charlesworth Jul 07 '12 at 14:15
  • @OliCharlesworth - what you say, makes a lot of sense, really. I have never thought about that, **good remark**! :) – Kiril Kirov Jul 07 '12 at 14:22
5

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());
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
Collin
  • 11,977
  • 2
  • 46
  • 60