开发者

STL sort question

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] usin开发者_高级运维g STL sort algorithm?


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];}
);


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


I'm not sure why so many of the answers posted are focusing on functors. There is no need for a functor with the OP's stated requirement. Here are 2 non-functor solutions:

1: Overload operator< in the Custom class

bool Custom::operator< (const Custom& rhs)
{
    return key[0] < rhs.key[0];
}

// can call sort(myvec.begin(), myvec.end());

2: Create a custom comparison 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>);


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜