gpt4 book ai didi

c++ - 根据数据对 std::map 进行排序(map->vector->sort)

转载 作者:行者123 更新时间:2023-11-28 07:32:36 24 4
gpt4 key购买 nike

我想根据数据(第二个字段)对 std::map 进行排序。但是,第二个字段本身是一个结构,我想根据其中一个元素进行排序。根据建议here及其 reference ,决定将 map 复制到一个 vector ,然后使用 std::sort。这是类实现

#include <iostream>
#include <vector>
#include <map>
#include <utility>

class foo() {
foo() {}
void bar()
{
aDeltaMap theDeltaMap;
// insert some elements to theDeltaMap
aDeltaVector theDeltaVec( theDeltaMap.begin(), theDeltaMap.end() );
std::sort(theDeltaVec.begin(), theDeltaVec.end(), descend_rep<deltaPair>() ); //ERROR
}
private:
typedef struct entry {
entry( int r, int mc ) : rep(r), missCounter(mc) {}
int rep;
int missCounter;
} aDeltaEntry;

typedef std::map< int, aDeltaEntry > aDeltaMap;
typedef std::pair< int, aDeltaEntry > deltaPair;
typedef std::vector< deltaPair > aDeltaVector;
struct descend_rep
: std::binary_function<deltaPair,deltaPair,bool>
{
inline bool operator()(const deltaPair& lhs, const deltaPair& rhs) { return lhs.second.rep > rhs.second.rep; };
};
};

在排序函数行,我得到这个错误

 error C2275: illegal use of this type as an expression
error C2059: syntax error : ')'

我错过了什么?

最佳答案

一个错误是descent_rep不是类模板,所以需要替换

descend_rep<deltaPair>()

通过

descend_rep()

你也应该使 descend_repbool operator() const,因为比较它的操作数不会改变它的状态。

关于c++ - 根据数据对 std::map 进行排序(map->vector->sort),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17378237/

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