STL sorting issue

I have a vector of structures:

vector<Custom> myvec; 

Custom is a structure:

 struct Custom { double key[3]; }; 

How to sort myvec by key [0]. key [1] or key [2] using the STL sorting algorithm?

+4
source share
4 answers

Write a custom comparator:

 template <int i> struct CustomComp { bool operator()( const Custom& lhs, const Custom& rhs) const { return lhs.key[i]<rhs.key[i]; } }; 

and then sort for example. using std::sort(myvec.begin(),myvec.end(),CustomComp<0>()); (this sorts by first key entry)

Or with a later compiler (with C ++ 0x lambda support):

 std::sort(myvec.begin(), myvec.end(), []( const Custom& lhs, const Custom& rhs) {return lhs.key[0] < rhs.key[0];} ); 
+12
source

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 :)

+10
source

I'm not sure why so many answers focused on functors. There is no need for a functor with an established OP requirement. Here are two non-functor solutions:

1: overload operator <in user class

 bool Custom::operator< (const Custom& rhs) { return key[0] < rhs.key[0]; } // can call sort(myvec.begin(), myvec.end()); 

2: create custom compare function

 template<int i> bool CustomLess(const Custom& lhs, const Custom& rhs) { return lhs.key[i] < rhs.key[i]; } // can call sort(myvec.begin(), myvec.end(), CustomLess<0>); 
+2
source
 bool CompareCustoms(const Custom& lhs, const Custom& rhs) { // Compare criteria here return (lhs.key[0] < rhs.key[0]); } sort(myvec.begin(), myvec.end(), CompareCustoms); 
0
source

All Articles