An Introduction to Standard template Library

The Standard Library is a fundamental part of the C++ Standard. It provides C++ programmers with a comprehensive set of efficiently implemented tools and facilities that can be used for most types of applications.

In this article, I present an introduction/tutorial on the Standard Template Library, which is the most important section of the Standard Library. I briefly present the fundamental concepts in the STL, showing code examples to help you understand these concepts. The article requires and assumes previous knowledge of the basic language features of the C++, in particular, templates (both function templates and class templates).

For a detailed description or listing of all the STL facilities, you should consult a reference material, such as Bjarne Stroustrup's The C++ Programming Language, 3rd edition , or Matthew Austern's Generic Programming and the STL.

Containers are used to manage collections of objects of a certain kind. There are several different types of containers like deque, list, vector, map etc.

Algorithms act on containers. They provide the means by which you will perform initialization, sorting, searching, and transforming of the contents of containers.

Iterators are used to step through the elements of collections of objects. These collections may be containers or subsets of containers.

Let us take the following program demonstrates the vector container (a C++ Standard Template) which is similar to an array with an exception that it automatically handles its own storage requirements in case it grows:

#include <iostream> #include <vector> using namespace std; int main() { // create a vector to store int vector<int> vec; int i; // display the original size of vec cout << "vector size = " << vec.size() << endl; // push 5 values into the vector for(i = 0; i < 5; i++){ vec.push_back(i); } // display extended size of vec cout << "extended vector size = " <<vec.size() << endl; // access 5 values from the vector for(i = 0; i < 5; i++){ cout << "value of vec [" << i << "] = " << vec[i] << endl; } // use iterator to access the values vector<int>::iterator v = vec.begin(); while( v != vec.end()) { cout << "value of v = " << *v << endl; v++; } return 0; }

Here are following points to be noted related to various functions we used in the above example:

The push_back( ) member function inserts value at the end of the vector, expanding its size as needed.
The size( ) function displays the size of the vector.
The function begin( ) returns an iterator to the start of the vector.
The function end( ) returns an iterator to the end of the vector.