Why sort() function causes compilation error when it is used for set of class objects

不羁的心 提交于 2019-12-25 19:53:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!