gpt4 book ai didi

c++ - 对 std::map 进行排序

转载 作者:行者123 更新时间:2023-11-30 04:17:10 25 4
gpt4 key购买 nike

我定义了这样一个 map

typedef   std::vector< int > aVector;
typedef std::map< int, aVector > aMap;
aMap theMap;

假设 map 最终包含这样的一些元素

10 [0 3 7] size=3
12 [40 2 30 3 10] size=5
20 [5 10] size=2
25 [6] size=1

我想根据 vector 的大小进行排序(例如 theMap->second.size())。所以结果会是

5 3 2 1

最快的方法是什么?基本思想是将大小推到另一个 vector 上,然后像这样调用 sort()

aVector v, sorted;
aMap::iterator it = theMap.begin();
for (; it != theMap.end(); ++it) {
v.push_back(it->second.size());
}
// using std sort!!

有没有更好的选择?

最佳答案

为什么不将 vector 作为键并使用自定义键比较函数/仿函数来比较键的大小?

您可以在 http://www.cplusplus.com/reference/map/map/map/ 中查看相关示例?

我现在还没有访问 C++ 编译器,但它会是这样的:

#include <map>

struct aComparisonStruct {
bool operator() (const aVector& lhs, const aVector& rhs) const {
return lhs.size > rhs.size;
}
};

int main () {
typedef std::vector<int> aVector;
typedef std::map<aVector, int, aComparisonStruct> aMap;

// Use your map

return 0;
}

但有一个问题:您不能再使用单键存在的属性,并且您将无法多次添加相同的 vector 。也许另一种实现方式更合适?

此外,使用指针作为键肯定会更好,但由于我无法编译,我不想混淆指针和引用并给你一些可能行不通的东西。

关于c++ - 对 std::map 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17264288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com