std::list<T,Allocator>::sort

Sorts the elements and preserves the order of equivalent elements. No references or iterators become invalidated.

# Declarations

void sort();
template< class Compare >
void sort( Compare comp );

# Parameters

# Return value

(none)

# Notes

std::sort requires random access iterators and so cannot be used with list. This function also differs from std::sort in that it does not require the element type of the list to be swappable, preserves the values of all iterators, and performs a stable sort.

# Example

#include <functional>
#include <iostream>
#include <list>
 
std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list)
{
    for (const int i : list)
        ostr << ' ' << i;
    return ostr;
}
 
int main()
{
    std::list<int> list{8, 7, 5, 9, 0, 1, 3, 2, 6, 4};
    std::cout << "initially: " << list << '\n';
 
    list.sort();
    std::cout << "ascending: " << list << '\n';
 
    list.sort(std::greater<int>());
    std::cout << "descending:" << list << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 1207C++98it was unclear whether iterators and/or references will be invalidatedkeep valid

# See also