Implementing a generic algorithm that can be used with any container

Implementing a generic algorithm allows programmers to easily implement their own algorithms, compatible with any container. In the following example, the contains() function can be used with any container:

template <typename Iterator, typename T>auto contains(Iterator begin, Iterator end, const T& v) {  for (auto it = begin; it != end; ++it) {    if (*it == v) {      return true;    }  }  return false;}

Vice versa, a new container can also use all the algorithms if it exposes the iterators. As a simple example, if we implement a two-dimensional Grid structure as shown below, where rows are exposed as pair of iterators:

Implementation of Grid structure: Illustration of corresponding ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.