I tried to overload <
operator for class and called the function as follows:
bool Edge::operator<(Edge const & e) const {
return this->GetCost() < e.GetCost();
}
in main()
sort(edge_set.begin(),edge_set.end());
In addition, I also tried to write a simple comparator function for the objects, defined in main.cpp and tried to invoke sort()
, however failed again:
bool edge_comparator(Edge& e1, Edge& e2){
return (e1.GetCost() < e2.GetCost());
}
in main()
sort(edge_set.begin(),edge_set.end(), edge_comparator);
I get a compilation error for those what I tried. What am I doing wrong here? How can I sort the set of objects?
Two problems. First, you cannot reorder the elements of a set. Their ordering criteria is determined upon construction, it is a fundamental part of the object. This is necessary in order for it to achieve O(log n) lookups, insertions, and deletions, which is part of the promises of
std::set
. By default, it will usestd::less<Edge>
, which should call youroperator<
. But you could also use youredge_comparator
function, like this:Second,
std::sort
can only be used on random access iterators or better, andstd::set
iterators are bi-directional.std::set
is a sorted associative container, so it cannot be re-sorted. The sorting criterion is applied on construction and on element insertion.Edit: You have a set of
Edge
pointers. If you want this to be sorted according to your own criteria, you can instantiate anstd::set
with the type of a functor that performs a less-than comparison between a pair ofEdge
pointers as second template argument:then
Edit 2: The question has been changed again, so it is not clear whether it deals with a set of pointers or not.