C++ STL algorithm, find_if() 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++ find_if() to locate the position of the first occurrence of an element in a range that satisfies a specified condition in C++ programming
To show: How to use the C++ algorithm, find_if() to locate the position of the first occurrence of an element in a range that satisfies a specified condition in C++ programming
// C++ STL algorithm, find_if()
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
bool great(int value)
{return (value>13);}
int main(void)
{
// list container
list <int> lst;
// list iterators
list <int>::iterator Iter;
list <int>::iterator result;
// pushing data, constructing the list
lst.push_back(13);
lst.push_back(9);
lst.push_back(10);
lst.push_back(22);
lst.push_back(31);
lst.push_back(17);
// print the data
cout<<"List lst data: ";
for(Iter = lst.begin(); Iter != lst.end(); Iter++)
cout<<*Iter<<" ";
cout<<endl;
// do the find_if() operation
cout<<"\nOperation: find_if(lst.begin(), lst.end(), great)"<<endl;
result = find_if(lst.begin(), lst.end(), great);
if(result == lst.end())
cout<<"There is no element greater than 13 in list lst."<<endl;
else
result++;
cout<<"There is an element greater than 13 in list lst, and it is followed by a "<<*(result)<<endl;
return 0;
}
Output examples:
List lst data: 13 9 10 22 31 17
Operation: find_if(lst.begin(), lst.end(), great)
There is an element greater than 13 in list lst, and it is followed by a 31
Press any key to continue . . .