【问题标题】:Sorting std::map based on the data (map->vector->sort)根据数据对 std::map 进行排序(map->vector->sort)
【发布时间】:2013-06-27 00:36:57
【问题描述】:

我想根据数据(第二个字段)对std::map 进行排序。然而,第二个字段本身是一个结构,我想根据它的一个元素进行排序。根据here 及其reference 的建议,决定将地图复制到矢量,然后使用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 : ')'

我错过了什么?

【问题讨论】:

    标签: c++ sorting map vector


    【解决方案1】:

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

    descend_rep<deltaPair>()
    

    通过

    descend_rep()
    

    您也应该将descend_repbool operator() 设为const,因为比较其操作数不会改变其状态。

    【讨论】:

    • 非常感谢。我认为没有必要编写模板,因为我只有一种数据类型。然后我忘了删除模板
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2021-03-26
    • 2018-09-05
    相关资源
    最近更新 更多