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

时间:2013-04-10 12:33:54

标签: c++ sorting stl

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

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);

我为我尝试的内容收到了编译错误。我在这做错了什么?如何对这组对象进行排序?

2 个答案:

答案 0 :(得分:3)

std::set是一个已排序的关联容器,因此无法重新排序。分类标准适用于构造和元素插入。

修改:您有一组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;

编辑2 :问题已再次更改,因此不清楚它是否处理了一组指针。

答案 1 :(得分:1)

两个问题。首先,您无法重新排序集合的元素。它们的排序标准是在构造时确定的,它是该对象的基本部分。这是必要的,以便它实现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迭代器是双向的。