对双精度地图进行排序
Sorting a map of pair and double
我有一张地图:map< pair < int , int > , long double> valore
.其中,该对表示我的坐标系,并且 (i,j( 坐标中的值加倍。
现在我必须从较小的双精度到较高的双精度对这张地图进行排序(显然坐标必须链接到相应的双精度(。有人可以帮助我吗?
您只需编写一个自定义比较器即可。在这里,您必须构建一个完整的对象,因为您需要根据键在特定映射中的值来比较键。这应该满足您的要求:
class Comparator {
std::map<std::pair<int, int>, double>& orig_map;
public:
Comparator(std::map<std::pair<int, int>, double>& orig_map)
: orig_map(orig_map) {}
bool operator () (const std::pair<int, int>& first,
const std::pair<int, int>& second) const {
return orig_map[first] < orig_map[second];
}
};
您可以使用它从原始地图构建特殊排序的地图:
std::map< pair < int , int > , long double> valore;
// load the map valore ...
// build a copy of valore sorted according to its value
Comparator comp(map);
std::map<std::pair<int, int>, double, Comparator> val_sorted(valore.begin(),
valore.end(), comp);
你可以迭代val_sorted
,它按其值排序
注意:切勿插入val_sorted
和valore
中不存在的元素。使用它的正确方法是在每次原始地图可能更改时创建一个新实例,或者至少清空它并重新加载它。
正如其他人所提到的,使用值无法直接对地图进行排序。 使用值对地图进行排序的一种方法如下。
- 创建一个矢量,将地图元素成对创建。 即
pair<Value, Key>
.在您的情况下,这将vector< pair<double, pair<int, int> > >
对 - 向量进行排序(使用自定义排序函数(,现在您可以按值对元素进行排序。
请参阅以下示例。(使用-std=c++11
选项编译(
#include <bits/stdc++.h>
using namespace std;
/* custom compare function. ascending order. Compares first elemens of p1 & p2 */
static bool custom_compare(const pair< double, pair<int, int> > & p1, const pair<double, pair<int, int> > & p2) {
return p1.first < p2.first;
}
void sortfn(map<pair<int, int>, double>& m) {
/* vector if pairs to hold values. */
vector< pair<double, pair<int, int> > > vec;
/* traverse the map and populate the vector */
for (auto it = m.begin(); it != m.end(); it++) {
vec.push_back(make_pair(it->second, it->first));
}
/* call sort method on the vector with custom compare method */
sort(vec.begin(), vec.end(), custom_compare);
for (auto it = vec.begin(); it != vec.end(); it++) {
cout<<it->first<<" ( "<<it->second.first<<", "<<it->second.second<<" )"<<endl;
}
}
int main() {
map<pair<int, int>, double> m;
m.insert(make_pair(make_pair(0, 0), 5));
m.insert(make_pair(make_pair(1, 1), 0));
m.insert(make_pair(make_pair(2, 2), 10));
sortfn(m);
return 0;
}
输出
0 ( 1, 1 )
5 ( 0, 0 )
10 ( 2, 2 )
由于下面的映射包含第一个参数作为整数对,第二个参数作为双精度,因此无法根据第一个参数(整数对(进行排序。
map< pair < int , int > , long double> valore
需要编写一个自定义函数,以便根据坐标进行排序。
相关文章:
- 是否有任何C++功能可以对地图进行排序?
- 如何使地图按值C++排序
- 我正在尝试按降序对地图进行排序,但没有得到预期的结果?
- 尝试按值对地图进行排序,但出现错误
- 对双精度地图进行排序
- 如何在OMNeT++中对地图进行排序?
- 多地图<矢量<int>>,字符>如何排序?
- 少的专业化<>适用于地图但不适用于排序
- 常量地图的意外排序
- C++按值对unordered_map或地图进行排序
- 如何对其中包含地图的列表进行排序
- 为什么我无法使用函数按值对地图进行排序?
- 如何在地图中插入对象以保持其排序
- 根据地图值的属性对地图进行排序
- C++,根据秒迭代对地图内容进行排序
- 如何以相反的顺序对地图进行排序
- 在 c++ 中对地图进行排序
- 获取按地图值排序的映射键向量的最快方法
- 标准::地图按值大小排序(设置<int>)
- 对基于地图C++集合重新排序的有效方法