以一个键和一对作为值对贴图进行排序

Sorting a map with a key and a pair as the value?

本文关键字:排序 一个      更新时间:2023-10-16

当我使用#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函数用于简单地将所有元素从源映射复制到目标映射。

实例

相关文章: