sky*_*oor 3 c++ sorting vector
假设我们有一个
vector<student> allstudent
Run Code Online (Sandbox Code Playgroud)
现在我想用不同的成员对学生进行排序,比如姓名,年龄,地址等.
我怎样才能做到这一点?
Jer*_*fin 26
创建一个仿函数来比较正确的字段,然后在排序时指定仿函数:
struct by_age {
bool operator()(student const &a, student const &b) const {
return a.age < b.age;
}
};
struct by_name {
bool operator()(student const &a, student const &b) const {
return a.name < b.name;
}
};
// sort by age
std::sort(students.begin(), students.end(), by_age());
// sort by name
std::sort(students.begin(), students.end(), by_name());
Run Code Online (Sandbox Code Playgroud)
从C++ 11开始,您可以使用lambda表达式"就地"进行比较,如下所示:
// sort by name:
std::sort(students.begin(), students.end(),
[](student const &a, student const &b) {
return a.name < b.name;
});
// sort by age:
std::sort(students.begin(), students.end(),
[](student const &a, student const &b) {
return a.age < b.age;
});
Run Code Online (Sandbox Code Playgroud)
这有两种简单的方法:
bool operator <(const student &lhs, const student &rhs)
{
return lhs.age < rhs.age;
}
std::sort(allstudent.begin(), allstudent.end()); // sorts by age
Run Code Online (Sandbox Code Playgroud)
或者写一个比较函数:
bool cmp(const student &lhs, const student &rhs)
{
return lhs.age < rhs.age; // here go your sort conditions
}
std::sort(allstudent.begin(), allstudent.end(), cmp); // also sorts by age
Run Code Online (Sandbox Code Playgroud)
std::sort(students.begin(), students.end(),
[](student const& stud1, student const& stud2) -> bool
{
return stud1.name() < stud2.name();
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您无法访问带有lambda语句的编译器:
std::sort(students.begin(), students.end(),
boost::bind(&student::name, _1) < boost::bind(&student::name _2));
Run Code Online (Sandbox Code Playgroud)
或者做棺材的方式.当你不得不这样做时,我倾向于避免使用标准算法......我很懒.