Sorting a list

This is a discussion on Sorting a list within the C++ Programming forums, part of the General Programming Boards category; I can sort a vector with the following code. However, if I change vector to list it doesn't work. Doesn't ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    65

    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?

    Code:
    #include <vector>
    #include <list>
    #include <iostream>
    #include <algorithm>
    #include <ctime>
    
    using namespace std;
    
    int main()
    {
    	srand(time(0));
    	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 << ' ';
    		it++;
    	}
    	cin.get();
    }

  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,009
    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
    Posts
    65
    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
    Posts
    7,317
    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, 01:46 PM
  3. Replies: 6
    Last Post: 03-02-2005, 01:45 AM
  4. compiler build error
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2003, 09:16 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21