Take the 2-minute tour ×

I have an Edge class defined as follows

class Edge {
    //constructors & destructors
    Edge(const Edge& orig);
    virtual ~Edge();
    Edge(unsigned const int, const string&, const string&);

    //getters & setters
    unsigned int GetCost() const {return cost;}

    //member functions
    bool operator<(const Edge*) const;
    unsigned int cost;  //cost of the edge
    string cities[2];   //cities that the edge connect

//cpp file
bool Edge::operator<(const Edge* e) const {
    cout << "edge" << endl;  //function is never invoked
    return this->cost < e->GetCost();

I want to keep those Edges (that are initially contained in a vector) in an Edge* set, and the corresponding code from main() is:

set<Edge*> edge_set;
vector<Edge*> edges;

while(edge_set.size() < K){ //randomly pick K edges that will form the tree

and I get the output:

Edge vector:
edges[0] cost = 136
edges[1] cost = 558
edges[2] cost = 872
edges[3] cost = 1615
edges[4] cost = 654
edges[5] cost = 994

Edge set:

I tried to define a function for overloading < operator in main as well, but I couldn't manage to get this set sorted that way either, i.e. couldn't get the overloaded < operator invoked. Also note that I different type of parameters (reference, pointer, object itself) for overloading <.

What am I doing wrong here? How can I fix this issue?

share|improve this question
I already explained this to you and gave a solution in your previous question. –  juanchopanza Apr 11 '13 at 9:33
oh, now I understood. Sorry about that, I upped your question tho. Clearly I wasn't thinking right. Now I see its the exact answer. Sorry again, I was pretty new to the topic thus couldn't understand the answer. –  Varaquilex Apr 12 '13 at 21:14
add comment

1 Answer

up vote 3 down vote accepted

You need operator < for both pointers. Since it's unreal by language rules and your operator is for object and pointer - default one (std::less<Edge*>) will be used. You can store objects, or you can write your functor, that will works with pointers and use it (set object should be declared like std::set<Edge*, Functor>).

Like this

struct CompareCost : public std::binary_function<const Edge*, const Edge*, bool>
   result_type operator () (first_argument_type f, second_argument_type s)
      return f->operator <(s);

std::set<Edge*, CompareCost> edge_set;
share|improve this answer
Thank you, that works. I have a few questions for this answer tho: Why did you use inheritance for the struct? what is std::binary_function<> ? Why does the operator has a return type of result_type and the arguments have first_argument_type and second_argument_type? Why didn't you write directly bool, const Edge*, const Edge* instead of them? –  Varaquilex Apr 11 '13 at 9:20
@Volkanİlbeyli en.cppreference.com/w/cpp/utility/functional/binary_function. You can not inherit from std::binary_function if you want. –  ForEveR Apr 11 '13 at 9:25
add comment

Your Answer


