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> v1, v2;
// vector iterator
vector <int>::iterator Iter1;
int i;
// pushing data in range
for (i = 0; i <= 5; i++)
{
v1.push_back(5 * i);
}
for (i = 0; i <= 2; i++)
{
v1.push_back(5);
}
for (i = 0; i <= 5; i++)
{
v1.push_back(5 * i);
}
for (i = 0; i <= 2; i++)
{
v1.push_back(5);
}
// print the data
cout<<"\nv1 vector: ";
for (Iter1 = v1.begin(); Iter1 != v1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl;
// searching v1 for first match to (5 5 5) under identity
vector <int>::iterator result1;
result1 = search_n(v1.begin(), v1.end(), 3, 5);
if (result1 == v1.end())
cout<<"\nThere is no match for a sequence (5 5 5) in v1 vector"<<endl;
else
cout<<"\nThere is at least one match of a sequence (5 5 5) in v1 vector and the first one begins at "
<<"position "<<int(result1 - v1.begin())<<endl;
// searching v1 for first match to (5 5 5) under twice
vector <int>::iterator result2;
result2 = search_n(v1.begin(), v1.end(), 3, 5);
if (result2 == v1.end())
cout<<"\nThere is no match for a sequence (5 5 5) in v1 vector under the equivalence predicate twice"<<endl;
else
cout<<"\nThere is a match of a sequence (5 5 5) under the equivalence\n predicate twice "
<<"in v1 vector and the first one begins at position "<<int(result1 - v1.begin())<<endl;
return 0;
}
Output examples:
v1 vector: 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 v1 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 v1 vector and the first one begins at position 6
Press any key to continue . . .