Stats

An Introductory STL tutorial

An STL starter that introduces the various collection types, strings, streams, iterators and methods of STL

<!-- Main HTML starts here -->

Introduction

STL provides a template based set of collection
classes, and methods for working on those collections.
The collection classes give the developer access to
fast and efficient collections. While the methods,
which are known as the algorithms, provide template
based collection manipulations functions.

The benefits of STL include

Type safe collections

Ease of use

Templates

If you are already familiar with templates then skip to
the next section. Otherwise read this section for a
brief tutorial on templates. A template can be thought
of as a macro with type checking. For example to
declare a template we would do the following:

This example declares a class Value, which stores a
parameterized value, _value, of type T. After the
keyword template, in the angled brackets, is a list of
parameters. The list tells the template what types will
be used in the template. A good analogy for the
template parameter list is the parameter list for a
class constructor. Like a constructor, the number of
arguments for the template can be from one to many.

Methods for a template that are declared outside the
class definition require the template keyword, as shown
above. To use the Value class to declare an array of
floats we would do:

Value<float> values[10]; // array of values of type float

This declares an array of values, the angled brackets
tells us that Value will store its value as a float.

If we wanted to declare a list to work with our
template based Value class we could do the following:

Here we have declared a template-based class that
stores a variable sized list of values.

STL Collection Types

Each STL collection type has its own template
parameters, which will be discussed later. What type of
collection you use is up to your needs and tastes. From
past experience, the vector and map classes are the
most useful. The vector class is ideal for simple and
complex collection types, while the map class is used
when an associative type of collection is needed. The
deque collection is excellent for use in systems that
have queued based processing, such as a message based
system.

vector

A collection of elements of type T.

list

A collection of elements of type T. The collection
is stored as a bi-directional linked list of
elements, each containing a member of type T.

To include the class definition use:

#include <list>

deque

A collection of varying length of elements of type
T. The sequence is represented in a way that
permits insertion and removal of an element at
either end with a single element copy, and
supports insertion and removal anywhere in the
sequence, but a sequence copy follows each
operation.

To include the class definition use:

#include <deque>

map

A collection for a varying length sequence of
elements of type pair<const Key, T>. The first
element of each pair is the sort key and the
second is its associated value. The sequence is
represented in a way that permits lookup,
insertion, and removal of an arbitrary element.
The key can be a simple as a number or string or
as complex a key class. The key class must support
normal comparison operations so that the
collection can be sorted or searched.

To include the class definition use:

#include <map>

set

A collection that controls a varying length
sequence of elements of type const Key. Each
element serves as both a sort key and a value. The
sequence is represented in a way that permits
lookup, insertion, and removal of an arbitrary
element.

To include the class definition use:

#include <set>

multimap

A collection of a varying length sequence of
elements of type pair<const Key, T>. The first
element of each pair is the sort key and the
second is its associated value. The sequence is
represented in a way that permits lookup,
insertion, and removal of an arbitrary element.

To include the class definition use:

#include <map>

multiset

A collection of a varying-length sequence of
elements of type const Key. Each element serves as
both a sort key and a value. The sequence is
represented in a way that permits lookup,
insertion, and removal of an arbitrary element.

To include the class definition use:

#include <set>

STL Strings

STL strings support both ascii and unicode character
strings.

string

A string is a collection of ascii characters that
supports both insertion and removal.

To include the string class definitions use:

#include <string>

wstring

A wstring is a collection of wide characters that
it supports both insertion and removal. In MFC the
string class is CString, which provides a Format
and other methods to manipulate the string.
CString has the advantage of providing methods
such as Format, TrimLeft, TrimRight and
LoadString. It is easy to provide a string-based
class that contains these methods.

To include the wstring class definitions use:

#include <xstring>

STL Streams

Streams provide the developer with classes that can
output to a container variable types of stream
elements.

stringstream

A string stream that supports insertions of
elements, and elements are inserted via the
overloaded operator <<. The method str() gives a
reference back to the underlying string, and the
c_str() can be used to get a constant pointer to
the string buffer.

wstringstream

A wstring stream that supports insertions of
elements, and elements are inserted via the
overloaded operator <<. The method str() gives a
reference back to the underlying string, and the
c_str() can be used to get a constant pointer to
the string buffer.

STL Collections General Class Methods

Returns a forward iterator pointing to the start
of the collection. It is commonly used to iterate
through a collection.

end

Returns a forward iterator pointing to one past
the end of the collection. It is commonly used to
test if an iterator is valid or in looping over a
collection.

rbegin

Returns a backward iterator pointing to the end of
the collection It is commonly used to iterate
backward through a collection.

rend

Returns a backward iterator pointing to one before
the start of the collection. It is commonly used
to test if an iterator is valid or in looping over
a collection.

clear

Erases all elements in a collection. If your
collection contains pointers the elements must be
deleted manually.

erase

Erase an element or range of elements from a
collection. To erase simply call erase with an
iterator pointing to the element or a pair of
iterator show the range of elements to erase.
Also, vector supports erasing based on array
index.

Standard Out and Input

STL also includes classes for printing to the standard
output streams. Like standard C++ the classes are cout
and wcout. To use them in a console application include
the file iostream. As an example:

Vector and Deque add and remove methods

We want to look briefly at adding/removing elements
from the vector and deque collections. These
collections are represented as an array, and to add an
element we use the push methods with back or front
depending on if we are adding at the front (start) or
back (end) of an array.

The general methods are:

push_back

Add element to end of collection.

push_front

Add an element to start of a collection.

back

Get a reference to element at end of collection

front

Get a reference to element at end of collection

pop_back Remove

element at end of collection

pop_front

Remove element at end of collection

As an example, suppose we want to build a message
processing system based on a message class:

With just a few lines of code we have created a general
messaging system, if we wanted an entire system we
could create a simple COM server that exposed a mail
interface, and that stored the messages using a message
list.

We have created a map, whose key is an integer, and
that stores strings.

Iterators

Iterators support the access of elements in a
collection. They are used throughout the STL to access
and list elements in a container. The iterators for a
particular collection are defined in the collection
class definition. Below we list three types of
iterators, iterator, reverse_iterator, and random
access. Random access iterators are simply iterators
that can go both forward and backward through a
collection with any step value. For example using
vector we could do the following:

This code will erase the first five elements of the
vector. Note, we are setting the last iterator to one
past the last element we of interest, and we test this
element against the return value of end (which give an
iterator one past the last valid item in a collection).
Always remember when using STL, to mark the end of an
operation use an iterator that points to the next
element after the last valid element in the operation.

The three types of iterators are:

iterator (forward iterator through collection)

Allows a collection to be traversed in the forward
direction. To use the iterator

The vector collection supports random access iterators.
Iterators are the most used type of access to the
collections of STL, and they are also used to
remove elements from collections. Look at the
following:

iterator element = begin(); erase(element);

This will set an iterator to the first element of
the collection and then remove it from the
collection. If we were using a vector we could do
the following

It is important to remember, when you get an iterator
to a collection do not modify the collection and then
expect to use the iterator. Once a collection has been
modified an iterator in most cases will become invalid.

Declaring collections

Each collection uses it’s template paramters to
determine what elements the collection will store.
Shown below is a list of the collections we are
discussing and beside each is the template pamaters. In
the parameters T denotes the element type to store in
the collection, A denotes the allocator (which
allocates elements), Key denotes the key for the
element, and Pred denotes how the collection will be
sorted.

This list looks somewhat daunting but it provides a
quick reference for the collections. In most cases you
will use the default arguments and your only concern
will be what you are storing and how it is stored. T
refers to what you will store, and for collections that
support a key; Key shows how the elements will be
associated.

From previous experience the vector, map and deque
classes are the most often used so we can use them as
an example for declaring a collection:

The first declaration declares a vector of integers,
the second declares a collection of integers, which
have a key of type string, and the last declares a
queue (or stack) of strings.

Another way to declare a collection is to derive a
collection from an STL collection as in the following:

class myVector : public vector<int> {};

Either method is useful, it a matter of preference.
Another important consideration is declaring the
iterators supported by the collection as separate
types. If we use the above example we would declare:

Algorithms

Up to this point we have discussed how to use STL at a
bare minimum, now we need to delve into the most
important part of the collections. How do we manipulate
a collection? For example, if we had list of strings,
what would we need to sort the list in alphabetical
order, or if we wanted to search a collection for a set
of elements that matched a given criterion. This is
where STL algorithms are used. In your visual studio
installation, under include directory, you will find an
include file, algorithm. In algorithm a set of template
based functions are declared. These functions can be
used to manipulate STL collections. The functions can
be categorized in the following: sequence, sorting and
numeric. Using these categories, we can list all of the
methods of algorithms:

Since this is an extensive list, we will only examine a
few of the methods in the algorithms. It is very
important to note that the methods here are templated
so we are not required to use the STL containers to use
the methods. For example, we could have a list of ints
and to sort this list then we could do:

How you use the algorithms is largely up to you, but
they provide a rich set of methods for manipulating
containers.

Multithreading Issues

STL is not thread protected, so you must provide locks
on your collections if they will be used in
multithreaded environment. The standard locking
mechanisms of Mutexes, Semaphores and Critical Sections
can be used. One simple mechanism for providing locking
is to declare a lock class. In this class the
constructor creates the lock, and the destructor
destroys the lock. Then provide lock() and unlock()
methods. For example:

Then declare a class that is derived from one of the
STL collections, and in the class override the access
methods to the collection that might cause an insertion
or deletion of an element. For example a general vector
class would be:

Conclusion

Hopefully I’ve given you a good tutorial on how to use
STL. If not then please try some of the web sites
listed below or drop by your local bookstore or
amazon.com and purchase one of the many books on the
subject. I believe STL can provide many benefits and I
hope you will to.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

I want 2 know that is it possible to use maps with in maps. Let me put an example for clarification.

Example: I want to make such a map whose key would be a UINT and its data would be a map which is also has key of UINT and again it has a data as map this map also has key of UINT and yet again it has a data as map, this map is my last map and it has key of UINT but its data is a string.

So, in short the construction of my map would be:

map<UINT, map<UINT, map<UINT, map<UINT, string>>>> test;

So, if this is possible then how could i make entries in each map and access each entry through itrators?

I am Sujay Ghosh here ; I have a question. When should the STL library be used vis a vis MFC, cause MFC has also classes which are similar to STL . The only difference I can figure out is that MFC Classes are CObject dependent while ordinary STL classes are not so . But is there any other issues other than this . If so , please let me know . My email id is sujayg_calin@yahoo.co.in.

STL is come along with newer version of C++ compiler.
Meaning, you should be able to use STL in other platform like Linux without having to install any component additionally. STL is part of C++ language itself.

If you just want to use containers, such as arrays and lists, and get things into and out of them then there's no real difference between using STL or MFC. But if you want to do more than this then STL has a very rich library of algorithms that you can apply, where MFC does not.

I started off uisng only a little STL when writing MFC code. But I now use it more and more. However, I still use CString because it has richer, more convenient, functionality than string. It all depends on what context I'm in.

I'm in college and I have a really simple problem which I've wasted almost an hour on the useless support section on the msn homepage.. anyway.. I know how to use templates, the problem is I CANT use them. I have visual studio professional edition 6.0 and I'm just trying to use a freakin' string. The computers at the college recognize
"#Include <iostream>" but on my computer I have to use "#include <iostream.h>". It doesn't allow me to use a template of any kind... it doesn't recognize "string variablename;" or any kind of template like a vector or list. I have windows 98 if that really makes a difference. All I want is to be able to use the STL. Is there an option or user preference I'm missing or what can I do? chances are I'll never find this page again to check back on a response so if someone could e-mail me a solution to: braddock@gmpexpress.net you would really make my day. It gets a little tedious using chars instead of strings and nodes and list classes instead of just declaring a list and being done with it.

so I capitalized, that's not my problem... my syntax is different than what I'm seeing on the site. I have to put ".h" at the end and it doesn't recognize anything like
using cout::std; or anything like that...
#include <string.h>
main()
{
std::string stuff;
return 0;
}

string.h is defanetly there. when I include it in my source it gives me strlen, strcpy, strcat, etc,. But when it comes to the string template it doesn't work.
in my include foler I have 970 files. On the CD it has 970 files... all of them are there. I think for whatever reason it doesn't recognize string but does recognize string.h is the same reason why it doesn't recognize "string whatever;"
Do you think it's because I'm using windows 98? I have the same thing used at my college but they have windows XP...

Just thought I'd repost since I havn't gotten an answer. Does anyone else have windows 98 and have/had the problem of not being able to use string and many other templates as well? It's just not working for me. read the messages before this one before you give me a solution I've already tried and didn't work.