P
Peter van Merkerk
I'm new to STL, so this might be a laugh...
The reason that std::list has a sort function is that it doesn't have
random access iterators, so it cannot work with the standalone
std::sort() function.
Take a look at the std::sort() function, which can sort containers with
random access iterators like std::vector:
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v;
v.push_back(10);
v.push_back(3);
v.push_back(30);
v.push_back(120);
v.push_back(5);
v.push_back(23);
std::sort(v.begin(), v.end());
return 0;
}
How do a sort the elemens in a vector? There is a sort() function on list,
but not on vector... right? But why?
The reason that std::list has a sort function is that it doesn't have
random access iterators, so it cannot work with the standalone
std::sort() function.
Suppose I would like a compare-function to compare the elements and not the
operator< for the elements, how i you do that?
Take a look at the std::sort() function, which can sort containers with
random access iterators like std::vector:
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v;
v.push_back(10);
v.push_back(3);
v.push_back(30);
v.push_back(120);
v.push_back(5);
v.push_back(23);
std::sort(v.begin(), v.end());
return 0;
}