按矢量超过1个字段

aaj*_*tak 0 c++ sorting compare vector

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

 #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 );
 }
Run Code Online (Sandbox Code Playgroud)

fbr*_*eto 7

我会像这样写:

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;
}
Run Code Online (Sandbox Code Playgroud)

这将允许您按顺序按名称,年龄和分数对记录进行排序.改变优先事项应该是一个简单的练习.


jsl*_*lap 5

您必须小心,您的排序标准是可传递的:如果x'y则y!<x.如果它不是传递的,则排序操作结果取决于调用之前数组的顺序,这可能是您不想要的.

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;
}
Run Code Online (Sandbox Code Playgroud)