简体   繁体   中英

How to create custom class used with std set copy assignment?

I try to create a custom class used with std::set . I know I need to provide a custom comparator for it so I overloaded the operator< . But when I try to copy the set with the code set<Edge> a; set<Edge> b = a; set<Edge> a; set<Edge> b = a; , I get the following error:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__functional_base:63:21: Invalid operands to binary expression ('const Edge' and 'const Edge')

class Edge {
public:
    Edge(int V, int W, double Weight):v(V),w(W),weight(Weight){}
    int other(int vertex){ return v ? w : vertex == w;}
    int v,w;
    double weight;
    friend std::ostream& operator<<(std::ostream& out, const Edge& e)
    {
        out<<e.v<<' '<<e.w<<' '<<"weight:"<<e.weight<<'\n';
        return out;
    }
    bool operator<(const Edge& other)
    {
        return weight < other.weight;
    }
};

Make

bool operator<(const Edge& other) const

as the comparison operator must be marked const . The keys in a std::set are const , so the operator< is invoked on a const instance, hence must be marked const .

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