0% found this document useful (0 votes)
70 views

CH 01

This document provides an overview of containers in the C++ Standard Template Library (STL). It describes the basic types of containers (sequence and associative), common container members like iterators and constructors, and specifics about each container type. The goal of containers is to store multiple objects, with different containers having characteristics like speed, size, and ease of use that depend on the required behavior.

Uploaded by

Hari Prasad
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

CH 01

This document provides an overview of containers in the C++ Standard Template Library (STL). It describes the basic types of containers (sequence and associative), common container members like iterators and constructors, and specifics about each container type. The goal of containers is to store multiple objects, with different containers having characteristics like speed, size, and ease of use that depend on the required behavior.

Uploaded by

Hari Prasad
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Containers, Iterators, and Algorithms

STL Pocket Reference

Ray Lischner
Containers
The C++ library has a basic suite of container types (deques,
lists, maps, sets, and vectors), which are described in this sec-
tion. This section also discusses the basic_string class tem-
plate because it is like a container. The non-container bitset
template is covered in the later section, “Miscellaneous.” The
fundamental purpose of a container is to store multiple
objects in a single container object. Different kinds of con-
tainers have different characteristics: speed, size, and ease of
use. The choice of container depends on the characteristics
and behavior you require.
To add items to a container, call an insert member func-
tion. You can also use push_back or push_front, if they are
available. Some containers offer additional means of adding
items, such as map::operator[].
To remove items from a container, call an erase member
function, or a specialized version such as pop_back or pop_
front. Some containers offer additional means of removing
items, such as list::remove.

NOTE
Note that the standard algorithms (see “Algorithms”) can-
not erase items from a container. Instead, the remove and
related algorithms reorganize the elements of a sequence
in preparation for calling erase.

Standard Containers
The standard containers fall into two categories: sequence and
associative containers. A sequence container preserves the
original order in which items were added to the container. An
associative container keeps items in ascending order (you can
define the order relation) to speed up searching.

4 | STL Pocket Reference


Sequence containers
The sequence containers are:
basic_string
string
wstring
These containers represent character strings. The string
class templates are not usually considered standard con-
tainers, but they meet most of the requirements of a
sequence container. The header is <string>.
deque
A deque (double-ended queue) supports fast (constant
complexity) insertions and deletions at the beginning and
end of the container. Inserting or deleting at any other
position is slower (linear complexity), but random access
to any item is fast. Items are not stored contiguously. The
header is <deque>.
list
A list supports rapid insertion or deletion at any position
but does not support random access. Items are not stored
contiguously. The header is <list>.
vector
A vector is like an array, except that the vector can grow
as needed. Items can be rapidly added or removed only
at the end. At other positions, inserting and deleting
items is slower. Random access to any item is fast. Items
are stored contiguously. The header is <vector>.

Associative containers
The associative containers are:
map
multimap
A map (or dictionary) is an associative container that
stores pairs of keys and associated objects. Pairs are
stored in ascending order of keys. A map requires unique

Containers | 5
keys. A multimap permits duplicate keys. The header for
map and multimap is <map>.
set
multiset
A set is an associative container that stores keys in
ascending order. A set requires unique keys. A multiset
permits duplicate keys. The header for set and multiset
is <set>.
The set and map containers perform insertions, deletions,
and searches with logarithmic complexity.

Container Adapters
In addition to the standard containers, the standard library
has several container adapters. An adapter is a class template
that uses a container for storage and provides a restricted
interface when compared with the standard containers.
Adapters do not have iterators, so they cannot be used with
the standard algorithms. The standard adapters are:
priority_queue
A priority queue is organized so that the largest element
is always the first. You can add an item to the queue,
examine the first element, or remove the first element.
The header is <queue>.
queue
A queue is a sequence of elements that lets you add ele-
ments at one end and remove them at the other end. This
organization is commonly known as FIFO (first-in, first-
out). The header is <queue>.
stack
A stack is a sequence that lets you add and remove ele-
ments only at one end. This organization is commonly
known as LIFO (last-in, first-out). The header is <stack>.

6 | STL Pocket Reference


Values
In C++, the containers are implemented as class templates.
The first template parameter is the type of the objects that
are to be stored in the container. You can use any type that
has value semantics, which means objects must behave as
ordinary values in the same manner as integers or other fun-
damental types. Values can be copied and assigned freely. An
original and its copy must compare as equal.
Sequence containers compare objects for equality with the ==
operator. Associative containers compare objects for equiva-
lence, which is slightly different from equality. Two objects,
A and B, are equivalent if A < B is false and B < A is false.
You can substitute a different function or functor for the <
operator, provided it implements a meaningful comparison
(called strict weak ordering in the standard). In particular, A
< A is always false, and if A < B and B < C, then A < C.
Associative containers take an additional template parame-
ter for the comparison function or functor. The default is
always less<>, which compares objects using the < operator.
Some associative containers require unique keys, while oth-
ers permit duplicate keys. Uniqueness is determined by test-
ing for equivalence, not equality.

Common Members
This section presents the members that are common to the
standard containers. Subsequent sections present the specif-
ics for each container type. Some members are found in every
container type, some in sequence containers only, and oth-
ers in associative containers only. Each of these categories is
covered in its own subsection.

Member types
Every container declares the following member typedefs:

Containers | 7
allocator_type
A synonym for the Allocator template parameter.
const_iterator
The iterator type for const values.
const_pointer
A synonym for the allocator’s const_pointer type.
const_reference
A const lvalue type for the items stored in the container.
Typically the same as the allocator’s const_reference
type.
difference_type
A signed integral type denoting the difference between
two iterators.
iterator
The iterator type.
pointer
A synonym for the allocator’s pointer type.
reference
An lvalue type for the items stored in the container. This
is typically the same as the allocator’s reference type.
size_type
An unsigned integral type that can hold any non-negative
difference_type value.
value_type
The type of item stored in the container. This is typically
the same as the first template parameter.
A container that supports bidirectional iterators also defines
the reverse_iterator and const_reverse_iterator types.

8 | STL Pocket Reference


These are iterators that run in the reverse direction, from the
last item to the first.
An associative container defines key_type as the key type,
compare_type as the type of the key compare function or
functor, and value_compare as the type of a function or func-
tor that compares two value_type objects.

Constructors and destructor


A container template has the constructors outlined in the fol-
lowing list. Whether the constructors are implemented using
overloading or default arguments is unimportant and left to
the implementation. If you supply an allocator object, it is
copied to the container; otherwise, a default allocator is con-
structed. In each of the following descriptions, container is
the name of the container class template.
container( )
container(allocator_type)
Constructs an empty container. Complexity is constant.
container(const container& that)
Constructs a container with a copy of all the items and
the allocator from that. Complexity is linear.
A sequence container has the following additional constructors:
container(size_type n, const value_type& x)
container(size_type n, const value_type& x,
allocator_type)
Constructs a container that has n copies of x. Complex-
ity is linear with respect to n.
template<typename InIter>
container(InIter first, InIter last)

Containers | 9
template<typename InIter>
container(InIter first, InIter last,allocator_type)
Constructs a container with copies of the items in the
range [first, last). Complexity is linear.
If InIter is an integral type, the container is initialized
with first copies of last (converted to value_type).
Complexity is linear.
An associative container has the following additional con-
structors:
container(key_compare compare)
container(key_compare compare, allocator_type)
Constructs an empty container that uses compare to com-
pare keys. Complexity is constant.
template<typename Inp>
container(Inp first, Inp last, key_compare compare)
template<typename Inp>
container(Inp first, Inp last, key_compare compare,
allocator_type)
Constructs a container with copies of the items in the
range [first, last), comparing keys with compare. Com-
plexity is linear.
All containers have a destructor:
~container( )
Calls the destructor for every object in the container, which
is equivalent to calling clear( ). Complexity is linear.

Common member functions


The following member functions are common to all con-
tainer types:
iterator begin( )
const_iterator begin( ) const
Returns an iterator that points to the first item of the
container. Complexity is constant.

10 | STL Pocket Reference


void clear( )
Erases all the items in the container. Complexity is linear.
bool empty( ) const
Returns true if the container is empty (size( ) == 0).
Complexity is constant.
iterator end( )
const_iterator end( ) const
Returns an iterator that points to one position past the
last item of the container. Complexity is constant.
erase(iterator p)
Erases the item that p points to. For a sequence con-
tainer, erase returns an iterator that points to the item
that comes immediately after the deleted item or end( ).
Complexity depends on the container.
For an associative container, erase does not return a
value. Complexity is constant (amortized over many
calls).
erase(iterator first, iterator last)
Erases all the items in the range [first, last). For a
sequence container, erase returns an iterator that points
to the item that comes immediately after the last deleted
item or end( ). Complexity depends on the container.
For an associative container, erase does not return a
value. Complexity is logarithmic, plus the number of
items erased.
allocator_type get_allocator( ) const
Returns a copy of the allocator object.
size_type max_size( ) const
Returns the largest number of items the container can
possibly hold. Complexity is usually constant.
container& operator=(const container& that)
Erases all items from this container and then copies all
the items from that. Returns *this. Complexity is linear.

Containers | 11
reverse_iterator rbegin( )
const_reverse_iterator rbegin( ) const
Returns a reverse iterator that points to the last item of
the container. Complexity is constant.
reverse_iterator rend( )
const_reverse_iterator rend( ) const
Returns a reverse iterator that points to one position before
the first item of the container. Complexity is constant.
size_type size( ) const
Returns the number of items in the container. Complex-
ity is usually constant. (See the “Lists” section for when
complexity is not constant.)
void swap(const container& that)
Swaps the elements of this container with that. Associa-
tive containers also swap their comparison functions.
Complexity is usually constant.
All containers have the equality and relational operators
defined, either as member functions or as functions at the
namespace level. The std::swap function is overloaded to call
the swap member function when swapping two container
objects of the same type.

Optional member functions


The following functions are optional. The standard contain-
ers provide only those functions that have constant complex-
ity (possibly amortized over many calls). The containers that
define these functions are shown in parentheses.
reference at(size_type n)
const_reference at(size_type n) const
Returns the item at index n, or throws out_of_range if n
>= size( ). (basic_string, deque, vector)

12 | STL Pocket Reference


reference back( )
const_reference back( ) const
Returns the last item in the container. Behavior is unde-
fined if the container is empty. (deque, list, vector)
reference front( )
const_reference front( ) const
Returns the first item in the container. Behavior is unde-
fined if the container is empty. (deque, list, vector)
reference operator[](size_type n)
const_reference operator[](size_type n) const
Returns the item at index n. Behavior is undefined if n >=
size( ). If n=size(), the behavior is undefined for most
containers. The exception is basic_string, which returns
a null character. (basic_string, deque, vector)
void pop_back( )
Erases the last item in the container. Behavior is unde-
fined if the container is empty. (deque, list, vector)
void pop_front( )
Erases the first item in the container. Behavior is unde-
fined if the container is empty. (deque, list)
void push_back(const value_type& x)
Inserts x as the new last item in the container. (basic_
string, deque, list, vector)
void push_front(const value_type& x)
Inserts x as the new first item in the container. (deque,
list)

Sequence member functions


All sequence containers define the following member func-
tions. Unless otherwise indicated, the complexity of each
depends on the container type.

Containers | 13
template <typename InputIterator>
void assign(InputIterator first, InputIterator last)
Replaces the container’s contents with the items in the
range [first, last) unless InputIterator is an integral
type, in which case the arguments are interpreted as
though they were cast as follows:
assign(static_cast<size_type>(first),
static_cast<value_type>(last));
Complexity is always linear.
void assign(size_type n, const T& value)
Replaces the container’s contents with n copies of value.
Complexity is always linear.
iterator insert(iterator p, const value_type& x)
Inserts x immediately before p and returns an iterator
that points to x.
void insert(iterator p, size_type n, const value_type& x)
Inserts n copies of x before p.
template<typename InIter>
void insert(iterator p, InIter first, InIter last)
Copies the values from [first, last) and inserts them
before p.

Associative member functions


All associative containers define the member functions dis-
cussed in the following list. In the descriptions of complex-
ity, N refers to the number of elements in the container, M
refers to the number of elements in the argument range (e.g.,
last – first), and count is the value that the function
returns. Some of these member functions seem to duplicate
standard algorithms (as discussed under the later section,
“Algorithms”), but the associative containers can implement
the member functions with better performance than the
generic algorithms.

14 | STL Pocket Reference


size_type count(const key_type& k) const
Returns the number of items equivalent to k. Complex-
ity is log N + count.
pair<const_iterator,const_iterator>
equal_range(const key_type& k) const
pair<iterator,iterator> equal_range(const key_type& k)
Returns the lower and upper bounds of a key. It is equiv-
alent to calling make_pair(lower_bound(k), upper_
bound(k)). Complexity is log N.
size_type erase(const key_type& k)
Erases all the items equivalent to k. Returns the number
of items erased. Complexity is log N + count.
const_iterator find(const key_type& k) const
iterator find(const key_type& k)
Finds an item equivalent to k and returns an iterator that
points to one such item, or end( ) if no such item is
found. Complexity is log N.
insert(const value_type& x)
Inserts x. If the container permits duplicate keys, insert
returns an iterator that points to the newly inserted item.
If the container requires unique keys, insert returns
pair<iterator,bool>, where the first element of the pair
is an iterator that points to an item equivalent to x, and
the second element is true if x was inserted or false if x
was already present in the container. Complexity is log N.
iterator insert(iterator p, const value_type& x)
Inserts x and returns an iterator that points to x. The iter-
ator p is a hint as to where x might belong. Complexity is
log N in general, but is amortized constant if the hint is
correct; that is, if x is inserted immediately after p.

Containers | 15
template<typename InIter> void
insert(InIter first, InIter last)
Copies the items from [first, last) and inserts each item
in the container. Complexity is M log(N + M), but is lin-
ear if the range is already sorted.
key_compare key_comp( ) const
Returns the key compare function or functor. Complex-
ity is constant.
const_iterator lower_bound(const key_type& k) const
iterator lower_bound(const key_type& k)
Returns an iterator that points to the first item in the set
that does not come before k. That is, the iterator points
to the position of its first occurrence if k is in the con-
tainer; otherwise, the iterator points to the first position
where k should be inserted. Complexity is log N.
value_compare value_comp( ) const
Returns the value compare function or functor. Com-
plexity is constant.
const_iterator upper_bound(const key_type& k) const
iterator upper_bound(const key_type& k)
Returns an iterator that points to the first item in the
container that comes after all occurrences of k. Complex-
ity is log N.

16 | STL Pocket Reference

You might also like