C++ STL algorithm, equal() program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ equal() to compare two ranges element by element either for equality or equivalence in a sense specified by a binary predicate in C++ programming

To show: How to use the C++ algorithm, equal() to compare two ranges element by element either for equality or equivalence in a sense specified by a binary predicate in C++ programming

 

// C++ STL algorithm, equal()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

// return whether second element is twice of the first

bool twice(int elem1, int elem2)

{ return ((elem1 * 2) == elem2);}

 

int main(void)

{

// vector containers

vector <int> vec1, vec2, vec3;

// vector iterators

vector <int>::iterator Iter1, Iter2, Iter3;

int i, j, k;

bool b, c, d;

 

// pushing data, constructing vectors

for(i = 10; i <= 15; i++)

vec1.push_back(i);

for(j = 0; j <= 5; j++)

vec2.push_back(j);

for(k = 10; k <= 15; k++)

vec3.push_back(k);

 

// print the data

cout<<"vec1 data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

cout<<"vec2 data: ";

for(Iter2 = vec2.begin(); Iter2 != vec2.end(); Iter2++)

cout<<*Iter2<<" ";

cout<<endl;

cout<<"vec3 data: ";

for(Iter3 = vec3.begin(); Iter3 != vec3.end(); Iter3++)

cout<<*Iter3<<" ";

cout<<endl;

 

// testing vec1 and vec2 vectors for equality based on equality

b = equal(vec1.begin(), vec1.end(), vec2.begin());

if(b)

cout<<"The vectors vec1 and vec2 vectors are equal based on equality."<<endl;

else

cout<<"The vectors vec1 and vec2 vectors are not equal based on equality."<<endl;

// testing vec1 and vec3 vectors for equality based on equality

c = equal(vec1.begin(), vec1.end(), vec3.begin());

if(c)

cout<<"The vectors vec1 and vec3 vectors are equal based on equality."<<endl;

else

cout<<"The vectors vec1 and vec3 vectors are not equal based on equality."<<endl;

// testing vec1 and vec3 vectors for equality based on twice()

d = equal(vec1.begin(), vec1.end(), vec3.begin(), twice);

if(d)

cout<<"The vectors vec1 and vec3 vectors are equal based on twice."<<endl;

else

cout<<"The vectors vec1 and vec3 vectors are not equal based on twice."<<endl;

return 0;

}

 

Output examples:

 

vec1 data: 10 11 12 13 14 15

vec2 data: 0 1 2 3 4 5

vec3 data: 10 11 12 13 14 15

The vectors vec1 and vec2 vectors are not equal based on equality.

The vectors vec1 and vec3 vectors are equal based on equality.

The vectors vec1 and vec3 vectors are not equal based on twice.

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index