Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Feb 3, 1999

Sorting With the sort() Algorithm

The generic algorithm sort() is part of the Standard Library. sort() takes two arguments of type const iterator that point to the beginning and the end of the sequence respectively:
 
#include <iostream>
#include <algorithm> //definition of sort()
#include <vector>
using namespace std;

void main()
{
  vector <int> vi;
  vi.push_back(7); 
  vi.push_back(1);
  vi.push_back(19);
  sort(vi.begin(), vi.end() );   // sort vi; default is ascending order
  cout<< vi[0]  <<", "<< vi[1] <<", "<< vi[2] <<endl;  // output: 1, 7, 19
}
When a descending order is preferred, you can use reverse iterators:
 
sort(vi.rbegin(), vi.rend() ); // now sort in descending order 
cout<< vi[0] <<", "<<vi[1]<<", "<<vi[2]<<endl; // output: 19, 7, 1
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap