“stable_sort()ing” a STL <list> in C++

走远了吗. 提交于 2019-12-10 15:57:04

问题


I think the question title is clear enough: is is possible to stable_sort() a std::list in C++? Or do I have to convert it to a std::vector?

I'm asking because I tried a simple example and it seems to require RandomAccessIterators, which a linked list doesn't have. So, how do I stable sort a std::list()?

EDIT: sample code that gives me an error:

#include <list>
#include <algorithm>
// ...
list<int> the_list;
stable_sort(the_list.begin(), the_list.end());

g++ gives me around 30 lines of errors (too long to paste), with some of them referring to RandomAccessIterators (and something called _merge_sort_loop). It's a little weird, since I've seen some merge sort implementations for linked lists and they are pretty much 'sequential'.


回答1:


std::list::sort is already stable. From the standard, section 23.2.24: "Notes: Stable: the relative order of the equivalent elements is preserved."



来源:https://stackoverflow.com/questions/1100561/stable-sorting-a-stl-list-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!