www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

STL Tutorial - Lesson 5: Generic Algorithms, Part 1

Introduction

by John Kopp

Support this site at no cost to you

There are three main components to the STL: container classes, iterators and generic algorithms. The containers are a set of ready to use data structures. The appropriate one is determined by the intended use. The generic algorithms provide a set of functions to modify, interpret and analyze the data in container objects. Iterators provide the connection between the containers and the algorithms. The generic algorithms take iterators as arguments to access data in container objects. Since they work on iterators, they have independence from the container type. The algorithms are called generic because they will work on any container via iterators.

You've seen how to use containers, iterators, function objects and adapters in the earlier lessons of this tutorial. In those lessons, the generic algorithms were also shown in examples. The goal of this lesson and the next two is to catalog many of the generic algorithms. Each will be presented along with an example demonstrating its use.

As a starting point, here is some general information about the algorithms that will be useful in what follows. Many of the generic algorithms are overloaded to allow the use of either a default predicate or a user specified predicate. For example:

sort(begin_iterator, end_iterator);    // sorts from smallest to largest
sort(begin_iterator, end_iterator, predicate);

Example: sort(v1.begin(), v1.end(), greater<int>());
                  // sorts from largest to smallest

Some of the generic algorithms have a basic version and a version, suffixed with _if, that accepts a predicate.

count(begin_iterator, end_iterator, value);    // counts elements == value
count_if(begin_iterator, end_iterator, predicate);

Example: count(v1.begin(), v1.end(), bind2nd(less<double>(),15.0));
                   // counts elements < 15.0

Some algorithms have versions that modify the original container object and versions that put the results into a new container object.

unique(begin_iterator, end_iterator);
            // remove successive duplicate elements
unique_copy(begin_source_iterator, end_source_iterator, begin_destination_iterator);
            // remove successive duplicate elements
            // putting results in the destination container.

Example: unique_copy(v1.begin(), v1.end(), v2.begin());

 

Previous Page       Next Page