C++ 使用 sort() 对 unordered_map 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31323135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort an unordered_map using sort()
提问by pratiksaha
I am trying to sort an unordered_map
using sort()
function but I keep getting a compiler error. Can anyone help?
我正在尝试对unordered_map
usingsort()
函数进行排序,但我不断收到编译器错误。任何人都可以帮忙吗?
bool comp(pair<char,int> a, pair<char,int> b) {
return a.second < b.second;
}
void rearrangeKDist(char str[], int d) {
int n = strlen(str);
unordered_map<char, int> table;
for (int i=0; i<n; i++) {
unordered_map<char, int>::iterator it = table.find(str[i]);
if (it == table.end()) {
table.insert(make_pair(str[i], 1));
} else {
it->second = it->second+1;
}
}
for (unordered_map<char, int>::iterator it=table.begin(); it!=table.end(); it++)
cout<<it->first<<" "<<it->second<<endl;
sort(table.begin(), table.end(), comp);
for (unordered_map<char, int>::iterator it=table.begin(); it!=table.end(); it++)
cout<<it->first<<" "<<it->second<<endl;
}
回答by Barry
This is impossible from both a compilation and logical standpoint. From a type standpoint, std::sort
requires:
从编译和逻辑的角度来看,这是不可能的。从类型的角度来看,std::sort
需要:
-RandomIt must meet the requirements of ValueSwappable and RandomAccessIterator.
-The type of dereferenced RandomIt must meet the requirements of MoveAssignable and MoveConstructible.
-RandomIt 必须满足 ValueSwappable 和 RandomAccessIterator 的要求。
-解引用的Random类型必须满足MoveAssignable和MoveConstructible的要求。
The iterator type on std::unordered_map
is a ForwardIterator, not a RandomAccessIterator, so the first requirement is unsatisfied. The type of the dereferenced iterator is pair<const Key, T>
, which is not MoveAssignable (can't assign to const
), so the second requirement is also unsatisfied.
on 的迭代器类型std::unordered_map
是 ForwardIterator,而不是 RandomAccessIterator,所以第一个要求不满足。解引用的迭代器的类型是pair<const Key, T>
,它不是 MoveAssignable(不能赋值给const
),所以第二个要求也不满足。
From a logical standpoint, sorting an unorderedcontainer makes no sense. It's unordered. And the complexity guarantees that unordered_map
is able to achieve require a very specific ordering that you shouldn't be, and aren't, allowed to mess with.
从逻辑的角度来看,对无序容器进行排序是没有意义的。它是无序的。并且unordered_map
能够实现的复杂性保证需要一个非常具体的排序,您不应该也不允许混淆。
If you want to "sort" your unordered_map
, put them in a vector
:
如果你想“排序”你的unordered_map
,把它们放在一个vector
:
std::vector<std::pair<char, int>> elems(table.begin(), table.end());
std::sort(elems.begin(), elems.end(), comp);