Reputation: 5825
I have a vector of vectors, as follows:
vector< vector<int> > intervals;
Basically, I need to sort the vector, using STL's sort (), but I need to sort 'intervals', for intervals[i][0]. So, sort the vector objects by the [0] element of each object.
How can I do this? Thank you in advance.
Upvotes: 1
Views: 87
Reputation: 227418
std::sort takes a comparator function of object as third argument, so you can define a less-than operator that takes two vector and compares their first elements.
bool foo(const std::vector<int>& a, const std::vector<int>& b) {
// in real life you may want to check vectors aren't empty.
// in real life you wouldn't call this foo either.
return a[0]<b[0];
}
int main() {
std::vector<std::vector<int>> v = ...;
std::sort(v.begin(), v.end(), foo);
}
Upvotes: 7