简体   繁体   English

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

[英]what's the difference between list.sort and std::sort?

I am trying to compile the following code using clang but got the following error. 我试图使用clang编译以下代码但得到以下错误。

I am wondering why using sort from the list class would work, but not std::sort . 我想知道为什么使用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(); /usr/include/c++/4.2.1/bits/stl_iterator.h:320:25:错误:二进制表达式的操作数无效('iterator_type'(又名'std :: _ List_iterator>')和'iterator_type'){return __y .base() - __ x.base(); } }

std::sort requires random access iterators, which std::list does not provide. std::sort需要随机访问迭代器, std::list不提供。 Consequently, std::list and std::forward_list implement their own member functions for sorting which work with their weaker iterators. 因此, std::liststd::forward_list实现了它们自己的成员函数,用于排序哪些函数与它们较弱的迭代器一起工作。 The complexity guarantees of those member functions are worse than those of the more efficient general algorithm. 这些成员函数的复杂性保证比更有效的通用算法更复杂。 [Whoops: see comments.] [哎呀:见评论。]

Moreover, the member functions can take advantage of the special nature of the list data structure by simply relinking the list nodes, while the standard algorithm has to perform something like swap (or something to that effect), which requires object construction, assignment and deletion. 此外,成员函数可以通过简单地重新链接列表节点来利用列表数据结构的特殊性质,而标准算法必须执行类似swap (或某种效果)的操作,这需要对象构造,赋值和删除。

Note that remove() is a similar case: The standard algorithm is merely some iterator-returning rearrangement, while the list member function performs the lookup and actual removal all in one go; 注意remove()是一个类似的情况:标准算法只是一些迭代器返回重新排列,而list成员函数一次执行查找和实际删除; again thanks to being able to take advantage of the knowledge of the list's internal structure. 再次感谢能够利用列表内部结构的知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM