Showing posts with label STL vector sorting example. Show all posts
Showing posts with label STL vector sorting example. Show all posts

Wednesday, May 11, 2011

STL vector sorting example

Here's a simple STL vector sorting example code in c++. a vector container is sorted by using sort() from <algorithm>, . It just traverses the items in a given STL list container.
[STL vector sorting example]

//Sorting a vector with 9 integers
#include <iostream.h>
#include <vector>
#include <algorithm>
void print( vector<int> ) ;//utility function outputs a $container
int main()
{
vector<int> a;
// Place 9,8,7,6,5,4,3,2,1 into the vector
for(int i=0; i<9;++i)
a.push_back(9-i);// put new element after all the others
print(a); // elements of a are (9,8,7,6,5,4,3,2,1)
sort( a.begin(), a.end() ); //in the STL <algorithm> library
print(a); // elements are nor in order.
}
 
void print( vector<int> a)
{
for(vector<int>::iterator ai=a.begin(); ai!=a.end(); ++ai)
cout << *ai << " ";
cout << endl;
cout << "----------------"<<endl;
}