C++ STL algorithm, adjacent_find() 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++ adjacent_find() to search for two adjacent elements that are either equal or satisfy a specified condition in C++ programming
To show: How to use the C++ algorithm, adjacent_find() to search for two adjacent elements that are either equal or satisfy a specified condition in C++ programming
// C++ STL algorithm, adjacent_find()
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
// returns whether second element is twice the first
bool twice(int elem1, int elem2)
{return ((elem1 * 2) == elem2);}
int main(void)
{
// list container
list<int> lst;
// list iterators
list<int>::iterator Iter;
list<int>::iterator result1, result2;
// pushing data, constructing a list
lst.push_back(14);
lst.push_back(17);
lst.push_back(31);
lst.push_back(31);
lst.push_back(10);
lst.push_back(20);
// print the data
cout<<"lst list data: ";
for(Iter = lst.begin(); Iter != lst.end(); Iter++)
cout<<*Iter<< " ";
cout<<endl<<endl;
// do the adjacent_find() operation
result1 = adjacent_find(lst.begin(), lst.end());
if(result1 == lst.end())
cout<<"There are not two adjacent elements that are equal."<<endl;
else
cout<<"There are two adjacent elements that are equal. They have a value of "<<*(result1)<<endl;
// another adjacent_find() operation
result2 = adjacent_find(lst.begin(), lst.end(), twice);
if(result2 == lst.end())
cout<<"\nThere are no two adjacent elements where the second is twice the first."<<endl;
else
{
cout<<"\nThere are two adjacent elements where the second is twice the first. They have values of "<<*(result2++);
cout<<" & "<<*result2<<endl;
}
return 0;
}
Output examples:
lst list data: 14 17 31 31 10 20
There are two adjacent elements that are equal. They have a value of 31
There are two adjacent elements where the second is twice the first. They have values of 10 & 20
Press any key to continue . . .