本文介绍了为什么sort()函数导致编译错误,当它用于一组类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为类重载< 运算符,并调用函数如下:

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

在main()中

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

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

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

在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?

推荐答案

两个问题。首先,你不能重新排序集合的元素。它们的排序标准是在构造时确定的,它是对象的基本部分。这是必要的,以便它实现O(log n)查找,插入和删除,这是 std :: set 的promise的一部分。默认情况下,它将使用 std :: less< Edge> ,它应该调用运算符< 。但您也可以使用 edge_comparator 函数,如下所示:

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

其次, std :: sort 用于随机访问迭代器或更好, std :: set 迭代器是双向的。

Second, std::sort can only be used on random access iterators or better, and std::set iterators are bi-directional.

这篇关于为什么sort()函数导致编译错误,当它用于一组类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 19:47