Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL sort question

Tags:

c++

sorting

stl

I have 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 STL sort algorithm?

like image 227
qutron Avatar asked Nov 29 '22 10:11

qutron


2 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 e.g. by using std::sort(myvec.begin(),myvec.end(),CustomComp<0>()); (this sorts by the first key entry)

Or with a more recent 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];}
);
like image 106
ltjax Avatar answered Dec 29 '22 02:12

ltjax


By using a a custom 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, while using a template enables the compiler to optimize for that specific index, it prevents you from selecting the index at runtime, e.g. based on userinput, so it's less flexible/can't do as much as the nontemplated version. And as we all know, premature optimization is evil :)

like image 41
etarion Avatar answered Dec 29 '22 01:12

etarion