对双精度地图进行排序

Sorting a map of pair and double

本文关键字:排序 地图 双精度      更新时间:2023-10-16

我有一张地图: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_sortedvalore中不存在的元素。使用它的正确方法是在每次原始地图可能更改时创建一个新实例,或者至少清空它并重新加载它。

正如其他人所提到的,使用值无法直接对地图进行排序。 使用值对地图进行排序的一种方法如下。

  • 创建一个矢量,将地图元素成对创建。 即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

需要编写一个自定义函数,以便根据坐标进行排序。