sorting a Vector

P

Peter van Merkerk

I'm new to STL, so this might be a laugh...
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;
}
 
C

Chris Theis

Peter van Merkerk said:
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.
[SNIP]

You can apply your own sorting criterion by supplying a binary predicate as
the third (optional) parameter to the sort function.

Regards
Chris
 
L

Lasse Skyum

I'm new to STL, so this might be a laugh...

How do a sort the elemens in a vector? There is a sort() function on list,
but not on vector... right? But why?

Suppose I would like a compare-function to compare the elements and not the
operator< for the elements, how i you do that?

Thanks :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top