How to sort an STL vector?

NativeCoder picture NativeCoder · May 3, 2010 · Viewed 155.1k times · Source

I would like to sort a vector

vector<myClass> object;

Where myclass contains many int variables. How can I sort my vector on any specific data variable of myClass.

Answer

avakar picture avakar · May 3, 2010
std::sort(object.begin(), object.end(), pred());

where, pred() is a function object defining the order on objects of myclass. Alternatively, you can define myclass::operator<.

For example, you can pass a lambda:

std::sort(object.begin(), object.end(),
          [] (myclass const& a, myclass const& b) { return a.v < b.v; });

Or if you're stuck with C++03, the function object approach (v is the member on which you want to sort):

struct pred {
    bool operator()(myclass const & a, myclass const & b) const {
        return a.v < b.v;
    }
};