c++ - 这段代码使用 std::sort 按值对 CPP 中的地图进行排序有什么问题?
问题描述
我正在尝试使用 std::sort 和自定义比较函数按值对 Map 进行排序。但我得到一个编译错误。
Ps:我不想使用 Lambda 函数。
我已经尝试在 dcompare 函数中使用迭代器变量作为参数。
class Solution {
public:
int foo(int n) {
unordered_map<int,int> M ;
// Inputs = {2,4,5,2,4,2,1}
M[4] = 2;
M[5] = 1;
M[2] = 3;
M[1] = 1;
for(auto it : M){
cout<<it.first<<" : "<<it.second<<endl;
}
sort(M.begin(), M.end(), dcompare);
for(auto it : M){
cout<<it.first<<" : "<<it.second<<endl;
}
return 0;
}
private:
static bool dcompare(const std::pair<int,int> itL, const std::pair<int,int> itR) {
return (itL.second < itR.second);
}
};
当我将变量更改为迭代器时,我得到了同样的错误
static bool dcompare(const map<int,int>::iterator itL, const map<int,int>::iterator itR)
{
return (itL->second < itR->second);
}
这是我得到的编译器错误:
stl_algo.h: In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_Rb_tree_iterator<std::pair<const int, int> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<bool (*)(std::pair<int, int>, std::pair<int, int>)>]':
stl_algo.h:4866:18: required from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = std::_Rb_tree_iterator<std::pair<const int, int> >; _Compare = bool (*)(std::pair<int, int>, std::pair<int, int>)]'
Line 15: Char 42: required from here
stl_algo.h:1969:22: error: no match for 'operator-' (operand types are 'std::_Rb_tree_iterator<std::pair<const int, int> >' and 'std::_Rb_tree_iterator<std::pair<const int, int> >')
std::__lg(__last - __first) * 2,
解决方案
无法重新排序地图的元素。Astd::map
是按键排序的,而 astd::unordered_map
是无序的,顾名思义。
错误本身告诉您std::sort
尝试对迭代器使用减法运算符,但映射迭代器没有这样的运算符。这反过来告诉您映射迭代器不是随机访问迭代器。std::sort
要求输入迭代器是随机访问迭代器。
一种解决方案是创建一个指向地图元素的指针数组并对数组进行排序。或者,如果您不再需要地图,您可以将元素本身移动到数组中。或者你可以复制元素。
另一种解决方案是使用多索引容器而不是地图。然而,标准库不提供这样的容器。多索引容器可以实现为一组具有共享节点的树。一个多节点将拥有每个索引树的子节点。因此,一个索引可以是您的地图的键查找,而另一个索引可以按值排序。
推荐阅读
- google-colaboratory - 如何在 Google Colab 中使用 TreeTagger?
- build - Spring Boot 和 React 应用程序的生产构建问题
- php - 以编程方式编辑 WooCommerce 应税运费时包括税费
- asp-classic - 经典 ASP 和 .Net Com DLL 网站在并发请求时挂起
- python - 每次我运行代码时,Chrome 都会打开并在几秒钟后关闭。为什么会关闭?
- bash - 如何使用 sed 或 awk 等命令行实用程序替换已知开始和停止位置之间的文件中的文本?
- flutter - Flutter 应用程序 - 空 GridTile 和条件
- c# - IIS REST 应用程序访问拒绝 COM+ 通信
- javascript - 如何一次播放数组中的一首歌曲反应js
- java - 日期为空的方法调用