16

如何vector通过比较pair.firstwhich is an来对它进行排序std::string?(不提供静态比较功能,也不使用 boost)。

4

5 回答 5

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

std::pair重载operator<首先按first元素排序,然后按second元素排序。因此,如果您只vector使用默认排序顺序 ( operator<) 进行排序,您将获得所需的顺序。

于 2011-01-05T23:19:04.567 回答
4

我真的很喜欢詹姆斯的回答,但您可能还想考虑另一种选择 - 只需将所有内容汇集到一个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)。

如果您真的必须使用向量,那么请使用 James 的答案。但是,如果您有一个成对向量,那么您很有可能真的想要一个std::map.

于 2011-01-05T23:36:06.377 回答
1

回答这个“重复问题”:链接:在 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
于 2018-11-15T07:01:32.630 回答
0

您可以使用自定义比较器.first仅对成对进行排序。

sort(begin, end,
     compose2(less<string>(),
              select1st<pair<string, bool> >(),
              select1st<pair<string, bool> >()));
于 2011-01-05T23:29:53.960 回答
0

您不需要提供任何比较函数,因为默认情况下 sort() 函数将按值的升序对向量进行排序。由于每个元素都是一对,因此如果一对的第一个值小于另一对的第一个值,则一对将小于另一对。

vector<pair<string,int>>v;
v = {{"xyz",1},{"pq",2}};   // Sample input
sort(v.begin(),v.end());    // Requires #include<algorithm> header
于 2021-08-30T11:06:08.703 回答