C++ 按多个字段对向量排序

C++ 按多个字段对向量排序,c++,vector,sorting,compare,C++,Vector,Sorting,Compare,如何按姓名、年龄和分数对以下代码进行排序。。。所有三个字段 #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

如何按姓名、年龄和分数对以下代码进行排序。。。所有三个字段

 #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 );
 }
#包括
#包括
#包括
结构学生
{
std::字符串名;
年龄、分数;
};
按多于1的字段(学生常数和左侧、学生常数和右侧)
{
//按姓名、年龄和分数排序
}
int main()
{
std::向量<学生>学生;
//填充学生
std::sort(students.begin()、students.end()、by\u more\u than\u 1\u字段);
}

我会这样写:

bool by_more_than_1_field( student_t const &lhs, student_t const &rhs )
{
    return lhs.name < rhs.name ||
           lhs.name == rhs.name && lhs.age < rhs.age ||
           lhs.name == rhs.name && lhs.age == rhs.age && lhs.score < rhs.score;
}
bool by_more__than_1_字段(学生常数和lhs、学生常数和rhs)
{
返回lhs.name

这将允许您按照姓名、年龄和分数的顺序对记录进行排序。更改优先级应该是一个简单的练习。

您必须小心您的排序标准是可传递的:如果是x'y,那么是y!<十,。 如果它不是可传递的,则排序操作的结果取决于调用前数组的顺序,这可能是您不希望看到的

bool by_more_than_1_field( student_t const &lhs, student_t const &rhs )
{
   if (lhs.name < rhs.name) 
      return true; 
   else if (rhs.name < lhs.name)
      return false;
   else // name equals.
      if (lhs. age  < rhs. age ) 
         return true; 
      else if (rhs. age  < lhs. age )
         return false;
      else // age and names equals
         return lhs.score < rhs.score;
}
bool by_more__than_1_字段(学生常数和lhs、学生常数和rhs)
{
if(左S.name<右S.name)
返回true;
else if(rhs.name
bool by_more_than_1_字段(学生常数和lhs、学生常数和rhs)
{
if(lhs.name
比其他的更容易维护,也更干净

#包括
#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 ){
      if(lhs.name ==rhs.name && lhs.age < rhs.age) return lhs.score<rhs.score;
      if(lhs.name==rhs.name) return lhs.age<rhs.age;
      return lhs.name<rhs.name;

}
#包括 #包括 结构学生 { std::字符串名; 年龄、分数; }; 按多于1的字段(学生常数和左侧、学生常数和右侧){
如果(lhs.name==rhs.name&&lhs.age#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 ){ if(lhs.name ==rhs.name && lhs.age < rhs.age) return lhs.score<rhs.score; if(lhs.name==rhs.name) return lhs.age<rhs.age; return lhs.name<rhs.name; }