2013-08-26 36 views
2

我有这样的载体:如何用多数据对矢量进行排序?

struct StatFaces 
{ 
    std::string faceName_1; 
    std::string faceName_2; 
    float percentagePerson ; 
}; 

std::vector<StatFaces> listFaces_; 

,我想那种载体。不过,我想分组。例如..

I have faceName_1 = john , faceName_2 = kate , percentagePerson = %90 
     faceName_1 = john , faceName_2 = nastia , percentagePerson = %95 
     faceName_1 = bill , faceName_2 = jamie , percentagePerson = %91 
     faceName_1 = bill , faceName_2 = anna , percentagePerson = %72 

output should be ; 

faceName_1 = bill , faceName_2 = jamie, percentagePerson = %91 
faceName_1 = bill , faceName_2 = anna , percentagePerson = %72 
faceName_1 = john , faceName_2 = nastia , percentagePerson = %95 
faceName_1 = john , faceName_2 = kate , percentagePerson = %90 

排序算法必须组firstName_1,然后排序根据percentagePerson

PS:我不擅长C++

回答

7

您可以通过自定义比较函数std::sort。这是使用std::tie平凡实现的:

#include <tuple> // for std::tie 

bool cmp(const StatFaces& lhs, const StatFaces& rhs) 
{ 
    return std::tie(lhs.face_name1, lhs.percentagePerson, lhs.faceName_2) < 
     std::tie(rhs.face_name1, rhs.percentagePerson, rhs.faceName_2); 
} 

然后

#include <algorithm> // for std::sort 

std::sort(listFaces_.begin(), listFaces_.end(), cmp); 

std::tie返回的左值参照参数的元组,并有一个辞书低于比较两个这些元组的比较bool operator<。其效果是您在两个StatFaces实例之间执行的字典比较低于字典。这由std::sort内部使用来对元素进行排序。

注意:std::tie可用于C++ 11实现。如果您没有C++ 11标准库实现,则可以使用标头<tr1/tuple>boost::tie中的std::tr1::tie。您也可以手动执行比较功能cmp。这是一个很好的练习,但它既乏味又容易出错。

+0

对不起,你能解释我更多,因为我不知道C++很好 – goGud

+0

+1真棒,我总是喜欢你的'元组'方法 – P0W

相关问题