c++ - list.sort 和 std::sort 有什么区别?

标签 c++ algorithm templates std

我正在尝试使用 clang 编译以下代码,但出现以下错误。

我想知道为什么使用 list 类中的 sort 可以工作,但不能使用 std::sort

#include <list>
#include <iostream>

int main(){
    std::string strings[] = {"hello", "nihao", "byebye", "yo"};
    std::list<std::string> cars(strings, strings+sizeof(strings) / sizeof(char **));

    // cars.sort(std::less<std::string>()); // compiles fine and produce a sorted list

    std::sort(cars.rbegin(), cars.rend(), std::less<std::string>() ); // this one won't compile

    for (std::list<std::string>::iterator it = cars.begin(); it != cars.end(); ++it)
        std::cout << *it << " - ";

    std::cout << std::endl;
    return 0;
}

/usr/include/c++/4.2.1/bits/stl_iterator.h:320:25: error: invalid operands to binary expression ('iterator_type' (aka 'std::_List_iterator >') and 'iterator_type') { return __y.base() - __x.base(); }

最佳答案

std::sort 需要随机访问 迭代器,std::list 不提供。因此,std::liststd::forward_list 实现了它们自己的成员函数来进行排序,这些函数与它们的较弱的迭代器一起使用。 这些成员函数的复杂性保证比更高效的通用算法的复杂性保证更差。[糟糕:请参阅评论。]

此外,成员函数可以通过简单地重新链接列表节点来利用列表数据结构的特殊性质,而标准算法必须执行类似 swap 的操作(或类似的操作),这需要对象的构造、分配和删除。

请注意 remove() 是一个类似的情况:标准算法只是一些迭代器返回的重新排列,而 list 成员函数执行查找和实际删除所有一气呵成;再次感谢能够利用列表内部结构的知识。

关于c++ - list.sort 和 std::sort 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8017215/

相关文章:

algorithm - 计算 (a^(2^N))%m 的最快算法?

c++ - 将函数作为模板类型传递并在 C++ 中扣除其类型

c++ - C2440 编译错误

c++ - 我可以将shared_ptr作为临时变量传递给线程吗?

c++ - CreateWindowEx WS_POPUP 为什么要打边框?

c++如何在不知道确切参数的情况下定义函数

c++ - 在 C++ 中使用函数模板作为模板模板参数

c++ - std::numeric_limits<double>::epsilon() 可以用来做什么?

python - 从列表列表中生成所有可能的组合

algorithm - Excel和VB的IRR函数的实现