2013-08-26 27 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

相關問題