Algorithms and Iterators


Although min() operates on pairs of values, most STL algorithms operate on sequences of elements. To operate on a wide range of sequences, including regular C arrays, STL containers, and other vendors' collections, STL algorithms only access data via the use of iterators.

For example, count() counts the number of items in a sequence that match a particular value. The first parameter to count() is an input iterator positioned at the start of the sequence. The second parameter is an input iterator positioned immediately beyond the last element of the sequence. The third parameter is the value to search for. The count() algorithm adds the number of matches to the fourth parameter, which is a reference to an integer.

Because a regular C pointer is upward compatible with an input iterator, count() can be used to count values in a regular C array.

Example <ospace/osstd/examples/alg2.cpp>
#include <iostream>
#include <algorithm>

int i[] = { 1, 4, 2, 8, 2, 2 };

void
main()
  {
  int n = 0; // Must be initialized, as count increments n.
  count( i, i + 6, 2, n );
  cout << "Count of 2s = " << n << "\n";
  }

count of 2s = 3

Because the iterators associated with most STL containers are upward compatible with input iterators, count() can also be used to count elements of a container. The following example uses count() to count matching elements in a vector .

Example <ospace/osstd/examples/alg3.cpp>
#include <iostream>
#include <algorithm>
#include <vector>

void
main()
  {
  vector< int > i;
  i.push_back( 1 );
  i.push_back( 4 );
  i.push_back( 2 );
  i.push_back( 8 );
  i.push_back( 2 );
  i.push_back( 2 );

  int n = 0; // Must be initialized, as count increments n.
  count( i.begin(), i.end(), 2, n );
  cout << "Count of 2s = " << n << "\n";
  }

count of 2s = 3

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.