问题
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?
回答1:
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 use std::less<Edge>
, which should call your operator<
. But you could also use your edge_comparator
function, like this:
std::set<Edge, bool(*)(Edge&,Edge&)> edge_set(edge_comparator);
Second, std::sort
can only be used on random access iterators or better, and std::set
iterators are bi-directional.
回答2:
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 an std::set with the type of a functor that performs a less-than comparison between a pair of Edge
pointers as second template argument:
struct EdgePtrCmp
{
bool operator()(const Edge* lhs, const Edge* rhs) const
{
return lhs->GetCost() < rhs->GetCost();
}
}
then
std::set<Edge*, EdgePtrCmp> s;
Edit 2: The question has been changed again, so it is not clear whether it deals with a set of pointers or not.
来源:https://stackoverflow.com/questions/15925976/why-sort-function-causes-compilation-error-when-it-is-used-for-set-of-class-ob