Using your own comparator.
struct CustomLess { size_t idx; CustomLess(size_t i) : idx(i) {} bool operator()(Custom const& a, Custom const& b) const { return a.key[idx] < b.key[idx]; } };
then
std::sort(myvec.begin(), myvec.end(), CustomLess(1)); // for 1
Note. I did not use a template because, using a template, it allows you to optimize the compiler for this particular index, it does not allow you to select an index at runtime, for example. based on userinput, so it is less flexible / cannot do as much as the version without using. And, as we all know, premature optimization is evil :)
source share