www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

STL Tutorial - Lesson 7: Generic Algorithms, Part 3

search, search_n

by John Kopp

Support this site at no cost to you

Algorithm search, search_n
Include file <algorithm>
Use search looks for the first occurrence for a match sequence within another sequence. search_n looks for a sequence of values repeated some number of times within another sequence.

#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;

int main() {

    list<string> l1, l2;
    list<string>::iterator iter;

    l1.push_back("I");
    l1.push_back("am");
    l1.push_back("indeed");
    l1.push_back("a");
    l1.push_back("cat");

    l2.push_back("a");
    l2.push_back("cat");

    iter = search(l1.begin(), l1.end(), l2.begin(), l2.end());

    if (iter != l1.end()) {
        cout << "a cat is found" << endl;
    }

    vector<int> v1;
    vector<int>::iterator i;

    v1.push_back(1);
    v1.push_back(5);
    v1.push_back(2);
    v1.push_back(2);
    v1.push_back(2);
    v1.push_back(4);

    i = search_n(v1.begin(), v1.end(), 3, 2);

    if (i != v1.end()) {
        cout << "v1 contains three 2's" << endl;
        cout << *i++ << " " << *i++ << " " << *i << endl;
    }

    return 0;

}

OUTPUT:
a cat is found
v1 contains three 2's
2 2 2

 

Previous Page       Next Page