以一个键和一对作为值对贴图进行排序
Sorting a map with a key and a pair as the value?
当我使用#include中的sort()方法时,我正试图对一个Key为String的映射和一对无符号long-long的映射进行排序;操作员,但当我通过地图开始和结束的地址时,我无法访问map.first、map.second.first或map.second.second
有人知道吗
map<string, pair<unsigned long long, unsigned long long>> ext_count;
sort(map.rbegin(), map.rend()); // to sort descending
bool operator < (map<string, pair<unsigned long long, unsigned long long>>& lhs, map<string, pair<unsigned long long, unsigned long long>>& rhs) {
return lhs.first < rhs.first;
}
正如注释所建议的,一种方法是将映射复制到具有不同排序顺序的映射。
这里有一个实现这一点的小例子:
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
// define the Sorter template class. If sortdir == true, then we sort ascending
template <bool sortdir = true>
struct Sorter
{
bool operator()(const std::string& left, const std::string& right)
{
if ( sortdir )
return left < right;
return left > right;
}
};
// our test maps
typedef std::pair<unsigned long long, unsigned long long> mapDataType;
// ascending map
std::map<std::string, mapDataType, Sorter<>> myMap =
{{"abc", {0,0}}, {"def",{0,1}}};
// descending map
std::map<std::string, mapDataType, Sorter<false>> myMap2; // descending map
// sample program
using namespace std;
int main()
{
// copy ascending map to descending map
std::copy(myMap.begin(), myMap.end(),
std::inserter(myMap2, myMap2.begin()));
}
请注意,我们在std::map
声明中使用了第三个参数来指定分类器谓词。
此外,std::copy
函数用于简单地将所有元素从源映射复制到目标映射。
实例
相关文章:
- 根据另一个矢量对一个矢量进行排序
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 给定一个枢轴点,按照它们与枢轴点构成的角度递增顺序对一组点进行排序
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- C++设置了一个用于排序的比较器和另一个用于唯一性的比较器
- 通过将其中一个模板更改为 muliset 后,我可以在 PBDS 排序集上使用计数功能<int>less_equal<int>
- 只对向量中的一个类成员进行排序,其他成员保持不变
- 为什么这个快速排序实现给出了一个奇怪的输出
- 使用迭代器进行合并排序中的一个缓冲区
- 使用C++对一个巨大文件中的文本行进行字典式外部排序
- 我想要一个改变数组快速排序的2个数字的函数
- 如何在一个巨大的文本文件中对整数进行排序
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- C++一个具有 2 个参数(___ _____,整数长度)的函数中的快速排序
- 按另一个向量对一个向量进行排序
- 我正在编写一个拆分为 3 的合并排序,我不知道为什么它不起作用
- 我写了一个快速的排序代码,逻辑似乎很正确,但是控制台上没有输出
- 尝试自定义一个函数来对不同种类元素的向量进行排序
- 冒泡排序一个结构数组
- 我如何在c++中排序一个整数字符串