Using std::reference_wrapper as the key in a std::map

前端 未结 3 623
再見小時候
再見小時候 2021-01-12 01:18

I have a bunch of objects in a class hierarchy and would like to make a std::map using references to those objects as the keys in the map. Its seems like

3条回答
  •  不要未来只要你来
    2021-01-12 02:03

    On Visual Studio 11 Beta, I get the same problem. Using the free version which calls the < operator solves the problem.

    #include
    #include
    using namespace::std;
    
    class Object { 
        int _n1;
    public:
    
        Object(int n = 0):_n1(n){};
        bool operator < (const Object& rhs) const {return this->_n1 < rhs._n1;} 
        friend ostream &operator << (ostream &stream, const Object& o) { stream << o._n1 << " "; return stream;}
    };
    
    struct ObjectLess{
    
        bool operator()(const Object& lhs, const Object& rhs) const 
        {
            return lhs, string> table;
    
        //Using the free function works
        std::map, string, ObjectLess> table;
    
        Object a(1);
        Object b(2);
        Object c(3);
    
    
        table[a]="One";
        table[c]="Three";
        table[b]="Two";
    
        for(auto y: table){
        cout << y.first << " " << y.second.c_str() << std::endl;
    }
    
    
        return 0;
    }
    

提交回复
热议问题