为什么sort()函数用于一组类对象时会导致编译错误

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

本文关键字:编译 错误 对象 一组 函数 sort 用于 为什么      更新时间:2023-10-16

我尝试为类重载<操作符,并按如下方式调用函数:

bool Edge::operator<(Edge const & e) const {
    return this->GetCost() < e.GetCost();
}
main ()

sort(edge_set.begin(),edge_set.end());

此外,我还尝试为在main.cpp中定义的对象编写一个简单的比较器函数,并试图调用sort(),但再次失败:

bool edge_comparator(Edge& e1, Edge& e2){
    return (e1.GetCost() < e2.GetCost());
}
main ()

sort(edge_set.begin(),edge_set.end(), edge_comparator);

我得到一个编译错误的那些我尝试。我哪里做错了?如何对对象集合进行排序?

std::set是一个已排序的关联容器,因此不能重新排序。排序准则应用于构造和元素插入。

Edit:您有一组Edge指针。如果您希望根据自己的标准对其进行排序,可以实例化一个std::set,其类型为一个函子,该函子在一对Edge指针之间执行小于比较,作为第二个模板参数:

struct EdgePtrCmp
{
  bool operator()(const Edge* lhs, const Edge* rhs) const
  {
    return lhs->GetCost() < rhs->GetCost();
  }
}
然后

std::set<Edge*, EdgePtrCmp> s;

Edit 2:问题再次更改,因此不清楚是否处理一组指针

有两个问题。首先,不能对集合中的元素重新排序。它们的排序标准是在构造时确定的,它是物体的基本组成部分。这对于实现O(log n)次查找、插入和删除是必要的,这是std::set承诺的一部分。默认情况下,它将使用std::less<Edge>,它应该调用operator<。但是你也可以使用edge_comparator函数,像这样:

std::set<Edge, bool(*)(Edge&,Edge&)> edge_set(edge_comparator);

第二,std::sort只能在随机访问迭代器或更好的迭代器上使用,std::set迭代器是双向的。