排序对和双的地图

问题描述 投票:0回答:3

我有一张地图:map< pair < int , int > , long double> valore。其中一对代表我的坐标系,两倍代表(i,j)坐标。

现在我必须从较小的双倍到较高的双重排序(显然,坐标必须链接到相应的双精度)。有人能帮我吗?

c++ sorting dictionary std-pair
3个回答
0
投票

正如其他人所提到的那样,使用这些值对地图进行排序是不可能的。使用值对地图进行排序的一种方法如下。

  • 使用地图元素作为一对创建矢量。即,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 )

1
投票

你只需要编写一个自定义比较器。在这里,您必须构建一个完整的对象,因为您需要根据特定映射中的值来比较键。这应该符合您的要求:

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


0
投票

由于下面的映射包含作为整数对的第一个参数和作为double的第二个参数,因此无法基于第一个参数(整数对)进行排序。

 map< pair < int , int > , long double> valore

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

© www.soinside.com 2019 - 2024. All rights reserved.