使用sort()对unordered_map进行排序 [英] sort an unordered_map using sort()
问题描述
我正在尝试使用 sort()
函数对 unordered_map
进行排序,但是我一直遇到编译器错误.有人可以帮忙吗?
I am trying to sort an unordered_map
using sort()
function but I keep getting a compiler error. Can anyone help?
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;
}
推荐答案
从编译和逻辑角度来看,这都是不可能的.从类型的角度来看, std :: sort
要求:
This is impossible from both a compilation and logical standpoint. From a type standpoint, std::sort
requires:
-RandomIt必须满足ValueSwappable和RandomAccessIterator的要求.
-取消引用的RandomIt的类型必须满足MoveAssignable和MoveConstructible的要求.
-RandomIt must meet the requirements of ValueSwappable and RandomAccessIterator.
-The type of dereferenced RandomIt must meet the requirements of MoveAssignable and MoveConstructible.
std :: unordered_map
上的迭代器类型是ForwardIterator,而不是RandomAccessIterator,因此不满足第一个要求.取消引用的迭代器的类型为 pair< const Key,T>
,它不是MoveAssignable(无法分配给 const
),因此第二个要求也不满足.
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.
从逻辑上讲,对无序容器进行排序是没有意义的.它是无序的.而且,复杂性保证了 unordered_map
能够实现的要求要求非常具体的顺序,您不应该也不允许这样做.
From a logical standpoint, sorting an unordered container 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
进行排序",请将它们放入 vector
:
If you want to "sort" your unordered_map
, put them in a vector
:
std::vector<std::pair<char, int>> elems(table.begin(), table.end());
std::sort(elems.begin(), elems.end(), comp);
这篇关于使用sort()对unordered_map进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!