按超过 1 个字段对向量进行排序
如何按姓名、年龄和分数对以下代码进行排序...所有三个字段
#include <string>
#include <vector>
#include <algorithm>
struct student_t
{
std::string name;
int age, score;
};
bool by_more_than_1_field( student_t const &lhs, student_t const &rhs )
{
// sort by name, age and score
}
int main()
{
std::vector< student_t > students;
// populate students
std::sort( students.begin(), students.end(), by_more_than_1_field );
}
How do I sort the below code by name, age and score... all three fields
#include <string>
#include <vector>
#include <algorithm>
struct student_t
{
std::string name;
int age, score;
};
bool by_more_than_1_field( student_t const &lhs, student_t const &rhs )
{
// sort by name, age and score
}
int main()
{
std::vector< student_t > students;
// populate students
std::sort( students.begin(), students.end(), by_more_than_1_field );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会这样写:
这将允许您按姓名、年龄和分数的优先顺序对记录进行排序。改变优先级应该是一个简单的练习。
I would write it like so:
This will allow you to sort the records prioritizing by name, age and score in that order. Changing the priorities around should be a simple exercise.
您必须小心您的排序标准是传递的:if x ' y then y !< x。
如果它不具有传递性,则排序操作结果取决于调用之前数组的顺序,这可能是您不希望的。
You have to be carefull that your sorting criteria is transitive: if x ' y then y !< x.
If it is not transitive, the sort operation result depends on the ordering of the array before the call, which you probably don't want.
比其他的更容易维护,而且也更干净!
Much easier to maintain than the others, and cleaner too!
解释 :
当您创建向量并应用排序函数时,请将此函数作为参数传递。
前任。
向量st;
然后进行排序
sort(st.begin(),st.end(), by_more_than_1_field)
其作用是该函数接受类 Student_t 的两个 const 参数。它接受 const,因此对象 Student_t 不可修改。然后按照函数中给出的方式进行比较。
Explanation :
when you make a vector and apply a sort function pass this function as parameter.
ex.
vector<strudent_t> st;
and then for sorting
sort(st.begin(),st.end(), by_more_than_1_field)
What this will do is the function accepts two const arguments of class student_t. It accepts const so the object student_t is not modifiable. It then compares as given in function.