Easy C++


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;



    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;


    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;


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


Previous Page       Next Page