简体   繁体   English

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

[英]Sorting std::map based on the data (map->vector->sort)

I want to sort a std::map based on the data (second field). 我想根据数据(第二个字段)对一个std::map进行排序。 However the second field itself is a structure and I want to sort based on one of its elements. 但是,第二个字段本身是一个结构,我想根据其元素之一进行排序。 Based on what is suggested here and its reference , decided to copy the map to a vector and then use std::sort . 根据此处建议的内容及其参考 ,决定将地图复制到向量中,然后使用std::sort Here is the class implementtion 这是类的实现

#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; };
      };
 };

At the line of sort function, I get this error 在排序功能的行,我得到了这个错误

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

What did I missed? 我错过了什么?

One error is that descent_rep is not a class template, so you need to replace 一个错误是descent_rep不是类模板,因此您需要替换

descend_rep<deltaPair>()

by 通过

descend_rep()

You should make descend_rep 's bool operator() const too, since comparing its operands does not change its state. 您也应该使descend_repbool operator() const ,因为比较其操作数不会改变其状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM