3

Possible Duplicate:
Sort list using stl sort function

The C++ standard library gives strict linear sequence container, linear sequence container, associative container.

std::sort() is available for all kinds of containers. But why only it provides sort for list. std::list::sort()?

Community
  • 1
  • 1
vrbilgi
  • 5,703
  • 12
  • 44
  • 60
  • 5
    presumably because there can be a more optimal implementation that can utilise implementation details of list - which may not be available to the general sort function – Nim Nov 03 '11 at 14:00
  • 1
    An explanation is given [here](http://stackoverflow.com/questions/2432857/sort-list-using-stl-sort-function). – Vlad Nov 03 '11 at 14:02
  • 1
    @Nim: Not really. See the responses. – John Dibling Nov 03 '11 at 14:06

2 Answers2

13

std::sort only works on random access containers. And the only non-random access container in the standard library that it makes sense to sort is std::list.

std::sort certainly doesn't work on associative containers as you seem to think. What sense would that make? Associative containers are accessed by the value of their key, not by position.

As noted by Mike, C++11 also has std::forward_list, which, by no accident, also has it's own sort function.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
7

std::sort only works for random access iterators, but a std::list only provides biderectional iterators. Since it therefore cannot be used with std::sort, it needs its own implementation, which is also likely to be more optimized for a doubly linked list.

Likewise you cannot use std::map or std::set iterators with std::sort. But for these you don't need it anyway, as they are always sorted.

As a side note, there are also std::map::find and the like. These are indeed not required, as you can use all iterators with std::find. But the member function versions provide optimized algorithms for the individual containers, which are more efficient than std::find's linear complexity.

Christian Rau
  • 45,360
  • 10
  • 108
  • 185