【发布时间】:2011-03-11 15:04:37
【问题描述】:
是否可以根据这些对象的任何属性轻松地对对象类型指针向量进行排序?
假设students是对象类型指针的向量,当对象student是Student的类型并且有两个方法student.studentAlias()和student.studentName()。如何根据别名对向量进行排序?
提前致谢。
【问题讨论】:
标签: c++ sorting attributes vector
是否可以根据这些对象的任何属性轻松地对对象类型指针向量进行排序?
假设students是对象类型指针的向量,当对象student是Student的类型并且有两个方法student.studentAlias()和student.studentName()。如何根据别名对向量进行排序?
提前致谢。
【问题讨论】:
标签: c++ sorting attributes vector
你可以使用仿函数:
#include <vector>
#include <algorithm>
class StudentAliasComparator
{
public:
bool operator()(const Student* left, const Student* right) const
{
return left->studentAlias() < right->studentAlias();
}
};
void SortVectorOfStudentByAlias(std::vector<Student*>& students)
{
std::sort(students.begin(), students.end(), StudentAliasComparator());
}
您也可以从 boost 或语言中使用 lambda(如果您使用 C++0x)。使用 C++0x 语法,它会类似于(无法检查,因为我现在无法访问支持 C++0x 的 C++ 编译器):
void SortVectorOfStudentByAlias(std::vector<Student*>& students)
{
std::sort(students.begin(), students.end(),
[](const Student* l, const Student* r) {
return l->studentAlias() < r->studentAlias(); })
}
【讨论】:
您可以使用 std::sort 算法进行排序:
template <class RandomAccessIterator, class StrictWeakOrdering>
void sort(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp);
只需提供一个对您感兴趣的属性执行小于比较的函数对象 (comp)。
【讨论】:
使用std::mem_fun 和一个包装器:
#include <algorithm>
#include <functional>
template <typename F>
struct CompareBy
{
bool operator()(const typename F::argument_type& x,
const typename F::argument_type& y)
{ return f(x) < f(y); }
CompareBy(const F& f) : f(f) {}
private:
F f;
};
template <typename F>
CompareBy<F> by(const F& f) { return CompareBy<F>(f); }
排序,做
std::vector<Student*> students;
std::sort(students.begin(), students.end(),
by(std::mem_fun(&Student::studentAlias))
);
如果要按成员变量排序,很遗憾没有std::mem_ptr。使用我的回答 there 中的想法来构建你自己的。
【讨论】: