c++ - Sort Vector<MyClass> on one of MyClass's data members? -
this question has answer here:
i create class, call myclass
has 3 data members- a, b , c. wish put many myclass
objects in std::vector<myclass>
, sort vector according data members.
is there elegant way of doing using stl? didn't want re-invent wheel , sure can't first. in java guess use comparator
.
the following should trick:
bool operator < (myclass const& lhs, myclass const& rhs) { return lhs.a < rhs.a; }
std::sort requires value_type of iterators less-than comparable, or in more technical terms, must form strict weak ordering. given code above, should able sort other type:
std::sort(std::begin(my_classes), std::end(my_classes));
assuming my_classes std::vector.
Comments
Post a Comment