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: Advanced
Feb 4, 1999

Using Predicate Objects to Alter Computation of a Generic Algorithm

A predicate is an expression that returns either true or false. Similarly, a function object that returns a Boolean value is a predicate object. The Standard Template Library has several predicate objects that can be used to alter the computation of a generic algorithm. For example, you can alter the computation of sort() by its predicate:
 
#include <functional> //definitions of STL predicates
#include <algorithm> //definition of sort 
#include <vector>
#include <iostream>
using namespace std;

int main()
{
  vector <int> vi;
  vi.push_back(9);
  vi.push_back(5);
  vi.push_back(10);
  sort(vi.begin(), vi.end(), greater<int> () );  // descending order
  cout<< vi[0] << '\t' << vi[1] << '\t' << vi[2] <<endl;   // output: 10  9  5
  sort(vi.begin(), vi.end(), less<int> () );   // now in ascending order
  cout<< vi[0] << '\t' << vi[1] << '\t' << vi[2] <<endl;   // output: 5  9  10
} 
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap