2009-11-11 73 views
0

如何排序姓名,年龄和得分下面的代码......所有这三个领域排序矢量

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

回答

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

我会写它像这样:

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

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

+1

我们的答案是相同的。很难说哪一个更容易阅读/维护... – jslap 2009-11-16 14:13:07

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

比别人更容易维护,和清洁呢!

+2

它会有一些奇怪的结果。如果rhs.name jslap 2009-11-16 14:10:29

-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){ 
     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; 

} 

说明: 当你犯了一个载体,应用排序功能,通过这个功能参数。
ex。 vector<strudent_t> st;
然后进行排序sort(st.begin(),st.end(), by_more_than_1_field)

这样做的功能是接受两个类student_t的常量参数。它接受const,所以对象student_t不可修改。然后比较函数中给出的。

+0

请编辑您的答案以包含对您的代码的解释。 – RedEyedMonster 2013-10-15 08:35:07