Hi,
Does STL and Vector provide the default sorting option?.
Hi,
Does STL and Vector provide the default sorting option?.
You probably want std::sort.
#include <algorithm>
#include <vector>
int
main()
{
std::vector<int> foo;
std::sort( foo.begin(), foo.end() );
return 0;
}
a similar example using two boost libraries is below.
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
#include <algorithm>
#include <iostream>
#include <vector>
int
main()
{
std::vector<int> foo = boost::assign::list_of(1)(4)(5)(10)(3)(2);
std::cout << "unsorted" << std::endl;
BOOST_FOREACH( const int i, foo ) {
std::cout << i << std::endl;
}
std::sort( foo.begin(), foo.end() );
std::cout << "sorted" << std::endl;
BOOST_FOREACH( const int i, foo ) {
std::cout << i << std::endl;
}
return 0;
}
Yes, there is sort()
in stl algorithms. You should look at http://www.cplusplus.com/reference/algorithm/sort/
The vector
class doesn't have a sort
function.
But there is a sort
which works on all iterator ranges. And vector
does expose iterators.
To sort a vector vec
:
#include <algorithm>
std::sort(vec.begin(), vec.end());
As other's have mentioned in their answers, there is std::sort function.
However, by "the default sorting option?." do you mean you want to sort a vector where T is a class you have defined. In that case, you have to implement "operator<" in your class.
For example,
class Foo
{
public :
Foo();
~Foo();
private :
int c;
};
std::vector<Foo> foovec;
std::sort(foovec.begin(), foovec.end());
To make sure that above "std::sort" line works, you need to define "operator<" in Foo.
class Foo
{
public :
Foo();
~Foo();
bool operator<(const Foo& rFoo) const;
private :
int c;
};
bool Foo::operator<(const Foo& rFoo) const
{
return(c < rFoo.c);
}