0

I have already used std::sort for array, now I want to use it for linked list Can I use std::sort for linked list. If it's able, how can I use it.

ThanhPhong
  • 11
  • 1
  • 4

2 Answers2

7

You can't, because std::sort requires random access iterators, and std::list provides only bidirectional iterators. Use std::list::sort instead.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
2

You may not use standard algorithm std::sort with container std::list because the algorithm uses random access iterators while container std::list has only a bidirectional iterator.

However std::list (and std::forward_list) has its own methods sort

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

For example

#include <iostream>
#include <list>
#include <cstdlib>
#include <ctime>
#include <algorithm>

int main() 
{
    const size_t N = 10;
    std::list<int> l( N );

    std::srand( ( unsigned )std::time( 0 ) );

    std::generate( l.begin(), l.end(), []{ return std::rand() % N; } );

    for ( int x : l ) std::cout << x <<' ';
    std::cout << std::endl;

    l.sort();

    for ( int x : l ) std::cout << x <<' ';
    std::cout << std::endl;

    return 0;
}

The output is

3 6 7 5 3 5 6 2 9 1 
1 2 3 3 5 5 6 6 7 9 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335