Thread: Sorting a list

  1. #1
    Registered User
    Join Date
    Jan 2008

    Sorting a list

    I can sort a vector with the following code. However, if I change vector to list it doesn't work. Doesn't sort() work with all STL containers?

    #include <vector>
    #include <list>
    #include <iostream>
    #include <algorithm>
    #include <ctime>
    using namespace std;
    int main()
    	vector<int> v;
    	for (int i = 0; i < 10; i++) v.push_back(rand());
    	sort(v.begin(), v.end());
    	vector<int>::iterator it = v.begin();
    	while (it != v.end()) {
    		cout << *it << ' ';

  2. #2
    Registered User
    Join Date
    Apr 2006
    The sort free function requires random access iterators. If you want to sort a list, use it's sort() method instead.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #3
    Registered User
    Join Date
    Jan 2008
    Is this an exception? Or should I expect that most STL algorithms will not work with most containers?

  4. #4
    Registered User
    Join Date
    Jan 2005
    Each algorithm works with specific kinds of containers. The documentation for the algorithms should specify. For example, the documentation for sort says that it works with random access iterators, so it will work with any container that provides random access iterators.

    If you're not sure, check the documentation for the type of iterator required, and familiarize yourself with the types of iterators provided by the different standard containers. Josuttis' or Meyers' STL books are good resources for this kind of information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  4. compiler build error
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2003, 10:16 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM