C ++结构排序 [英] C++ struct sorting
本文介绍了C ++结构排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 我有一个自定义结构的向量,每次都需要按照不同的条件进行排序
- 实施运算符<将仅允许一个条件
- 但是我希望能够在每次调用C ++标准排序时指定排序标准.
该怎么做?
- 请注意,运行时效率更高..
谢谢
推荐答案
您可以使用第三个参数来定义在排序算法的每次运行中要使用的比较函数:
You can define what comparison function to use in each run of the sort algorithm by using the third argument:
template <class RandomAccessIterator, class StrictWeakOrdering>
void sort(RandomAccessIterator first, RandomAccessIterator last,
StrictWeakOrdering comp);
一个简单的例子:
struct person {
std::string name;
int age;
};
bool sort_by_name( const person & lhs, const person & rhs )
{
return lhs.name < rhs.name;
}
bool sort_by_age( const person & lhs, const person & rhs )
{
return lhs.age < rhs.age;
}
int main() {
std::vector<person> people;
// fill in the vector
std::sort( people.begin(), people.end(), sort_by_name );
std::sort( people.begin(), people.end(), sort_by_age );
}
这篇关于C ++结构排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文