C++ STL algorithm, search_n() code 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++ search_n() to search for the first subsequence in a range that of a specified number of elements having a particular value or a relation to that value as specified by a binary predicate in C++ programming

To show: How to use the C++ algorithm, search_n() to search for the first subsequence in a range that of a specified number of elements having a particular value or a relation to that value as specified by a binary predicate in C++ programming

 

// C++ STL algorithm, search_n()

#include <vector>

#include <list>

#include <algorithm>

#include <iostream>

using namespace std;

 

// return whether second element is twice the first

bool twice(int elem1, int elem2)

{return 2 * elem1 == elem2;}

 

int main(void)

{

// vector containers

vector <int> vec1, vec2;

// vector iterator

vector <int>::iterator Iter1;

int i;

 

// pushing data in range

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

vec1.push_back(5*i);

for(i = 0; i <= 2; i++)

vec1.push_back(5);

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

vec1.push_back(5*i);

for(i = 0; i <= 2; i++)

vec1.push_back(5);

 

// print the data

cout<<"vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// searching vec1 for first match to (5 5 5) under identity

vector <int>::iterator result1;

result1 = search_n(vec1.begin(), vec1.end(), 3, 5);

if(result1 == vec1.end())

cout<<"\nThere is no match for a sequence (5 5 5) in vec1 vector."<<endl;

else

cout<<"\nThere is at least one match of a sequence (5 5 5) in vec1 vector and the first one begins at position "<<int(result1 - vec1.begin())<<endl;

// searching vec1 for first match to (5 5 5) under twice

vector <int>::iterator result2;

result2 = search_n(vec1.begin(), vec1.end(), 3, 5);

if(result2 == vec1.end())

cout<<"\nThere is no match for a sequence (5 5 5) in vec1 vector under the equivalence predicate twice."<<endl;

else

cout<<"\nThere is a match of a sequence (5 5 5) under the equivalence\npredicate twice"

<<" in vec1 vector and the first one begins at position "<<int(result1 - vec1.begin())<<endl;

return 0;

}

 

Output examples:

 

vec1 vector data: 0 5 10 15 20 25 5 5 5 0 5 10 15 20 25 5 5 5

There is at least one match of a sequence (5 5 5) in vec1 vector and the first one begins at position 6

There is a match of a sequence (5 5 5) under the equivalence

predicate twice in vec1 vector and the first one begins at position 6

Press any key to continue . . .

 

 

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