我有结构矢量:
vector<Custom> myvec;
Run Code Online (Sandbox Code Playgroud)
自定义是一种结构:
struct Custom
{
double key[3];
};
Run Code Online (Sandbox Code Playgroud)
如何排序myvec会通过键[0].key [1]或key [2]使用STL排序算法?
ltj*_*jax 12
编写自定义比较器:
template <int i> struct CustomComp
{
bool operator()( const Custom& lhs, const Custom& rhs) const
{
return lhs.key[i]<rhs.key[i];
}
};
Run Code Online (Sandbox Code Playgroud)
然后排序,例如通过使用std::sort(myvec.begin(),myvec.end(),CustomComp<0>());
(按第一个键输入排序)
或者使用更新的编译器(支持c ++ 0x lambda):
std::sort(myvec.begin(), myvec.end(),
[]( const Custom& lhs, const Custom& rhs) {return lhs.key[0] < rhs.key[0];}
);
Run Code Online (Sandbox Code Playgroud)
eta*_*ion 10
通过使用自定义比较器.
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];
}
};
Run Code Online (Sandbox Code Playgroud)
然后
std::sort(myvec.begin(), myvec.end(), CustomLess(1)); // for 1
Run Code Online (Sandbox Code Playgroud)
注意:我没有使用模板,因为虽然使用模板使编译器能够针对该特定索引进行优化,但它会阻止您在运行时选择索引,例如基于用户输入,因此它不太灵活/不能做多少作为非模板版本.众所周知,过早的优化是邪恶的:)