簡體   English   中英

對std :: vector進行排序 <std::pair<std::string,bool> &gt;由字符串?

[英]Sorting a std::vector<std::pair<std::string,bool>> by the string?

如何通過比較pair.first是一個std::string來對這個vector進行排序? (不提供靜態比較功能,也不使用boost)。

std::vector<std::pair<std::string, bool> > v;
std::sort(v.begin(), v.end());

std::pair重載operator<首先按第first元素排序,然后按second元素排序。 因此,如果您只使用默認排序順序( operator< )對vector進行排序,您將獲得所需的排序。

我真的很喜歡詹姆斯的回答,但還有一個你可能想要考慮的選擇 - 只需將所有內容匯集到一個std::map

std::map<std::string, bool> myMap(v.begin(), v.end());

或者,如果您有重復的字符串,則std::multimap

std::multimap<std::string, bool> myMultiMap(v.begin(), v.end());

這確實具有額外的優勢,如果您需要添加或刪除新的鍵/值對,則可以在O(lg n)中執行此操作,而不是對於已排序的向量的O(n)。

如果你真的必須使用矢量,那么請回答詹姆斯的回答。 但是,如果你有一對對矢量,你很可能真的想要一個std::map

您可以使用自定義比較器在對' .first上訂購。

sort(begin, end,
     compose2(less<string>(),
              select1st<pair<string, bool> >(),
              select1st<pair<string, bool> >()));

回答這個問題的“重復問題”:鏈接: 用C ++中的第一個元素和第二個元素對第一個元素的對矢量進行排序?

bool cmp(const pair<int,int>&x,const pair<int,int>y){
if(x.first==y.first){
   return(x.second<y.second);
}
return(x.first<y.first);
}

array of pairs before:
5 2
4 2
8 2
8 3
8 1
array of pairs after:
4 2
5 2
8 1
8 2
8 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM