-
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();
}
-
The sort free function requires random access iterators. If you want to sort a list, use it's sort() method instead.
-
Is this an exception? Or should I expect that most STL algorithms will not work with most containers?
-
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.