сортировать вектор по более чем 1 полю - PullRequest
0 голосов
/ 11 ноября 2009

Как отсортировать приведенный ниже код по имени, возрасту и баллу ... все три поля

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

Ответы [ 4 ]

7 голосов
/ 11 ноября 2009

Я бы написал так:

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

Это позволит вам отсортировать записи по приоритетам по имени, возрасту и баллам в указанном порядке. Изменение приоритетов должно быть простым упражнением.

5 голосов
/ 11 ноября 2009

Вы должны быть осторожны, что ваши критерии сортировки транзитивны: если 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;
}
0 голосов
/ 15 октября 2013
#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<strudent_t> st;
а затем для сортировки sort(st.begin(),st.end(), by_more_than_1_field)

Для этого функция принимает два константных аргумента класса student_t. Он принимает const, поэтому объект student_t не может быть изменен. Затем он сравнивается, как указано в функции.

0 голосов
/ 12 ноября 2009
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;
}

Гораздо проще в обслуживании, чем другие, и чище тоже!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...