简体   繁体   中英

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

I want to sort a std::map based on the data (second field). 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 . 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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