【问题标题】:sort vector by more than 1 field按超过 1 个字段对向量进行排序
【发布时间】:2009-11-11 19:55:42
【问题描述】:

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

 #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 );
 }

【问题讨论】:

    标签: c++ vector sorting compare


    【解决方案1】:

    我会这样写:

    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;
    }
    

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

    【讨论】:

    • 我们的答案是等价的。很难说哪一个更容易阅读/维护……
    【解决方案2】:

    您必须小心,您的排序标准是可传递的:如果 x ' y then 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;
    }
    

    【讨论】:

      【解决方案3】:
      bool by_more_than_1_field( student_t const& lhs, student_t const& rhs )
      {
          if( lhs.name < rhs.name )
              return true;
          else if( lhs.age < rhs.age )
              return true;
          else if( lhs.score < rhs.score )
              return true;
      
          return false;
      }
      

      比其他的更容易维护,也更干净!

      【讨论】:

      • 会有一些奇怪的结果。如果 rhs.name
      【解决方案4】:
      #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;
      
      }
      

      说明: 当你创建一个向量并应用一个排序函数时,将此函数作为参数传递。
      前任。 vector&lt;strudent_t&gt; st;
      然后对 sort(st.begin(),st.end(), by_more_than_1_field) 进行排序

      这将做的是该函数接受类 student_t 的两个 const 参数。它接受 const 所以对象 student_t 是不可修改的。然后它按照函数中给定的方式进行比较。

      【讨论】:

      • 请编辑您的答案以包括对您的代码的解释。
      猜你喜欢
      • 2017-11-13
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多