0% found this document useful (0 votes)
41 views36 pages

Standard Template Library Quick Reference: Containers

The Standard Template Library provides common general purpose container classes like vector, deque, list, stack, queue, and associative containers set and map that efficiently store and organize objects, iterators allow processing elements in containers, and the document describes the containers, their features, performance characteristics, and iterator categories.

Uploaded by

Ayush Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views36 pages

Standard Template Library Quick Reference: Containers

The Standard Template Library provides common general purpose container classes like vector, deque, list, stack, queue, and associative containers set and map that efficiently store and organize objects, iterators allow processing elements in containers, and the document describes the containers, their features, performance characteristics, and iterator categories.

Uploaded by

Ayush Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Standard Template Library Quick Reference

Containers
Containers are general-purpose template classes that are designed to store
objects of almost any type. They are useful by themselves, but become even
more powerful when combined with other concepts such as iterators and
algorithms.

Standard Containers

Name Header Description


vector<T, Alloc> <vector> or Acts very similar to a standard array that
<vector.h> can grow to accommodate additional
elements.
deque<T, Alloc> <deque> or This is a double-ended queue which is
<deque.h> efficient at adding or removing elements
from either the beginning or end of the
queue.
list<T, Alloc> <list> or <list.h> A doubly-link list container that uses
pointers to nodes. One pointer stores the
location of the next node and the second
pointer stores the location of the previous
node. Faster than the vector and deque
containers at some operations, notably
adding or removing elements from the
middle of the container.

NOTE: The Alloc parameter allows you to define your own custom memory
allocator if needed. A custom memory allocator is useful is some situations such
as when working with embedded systems which do not have general-purpose
malloc/free or new/delete operators.

Container Operation Costs

Operation C-Array vector deque list


Insert/erase at start N/A linear constant constant
Insert/erase at end N/A constant constant constant
Insert/erase in middle N/A linear linear constant
Access first element constant constant constant constant
Access last element constant constant constant constant
Access middle element constant constant constant linear
Operation C-Array vector deque list
Overhead none low medium high

Vector Advantages

– Vectors can be dynamically resized; when you run out of space it automatically
grows
– Elements of a vector can be added or removed from the interior without needing
to write custom code
– You can quickly access the start the or end of the vector, without knowing it
size in advance
– You can iterate forward or backward through a vector
– It is a simple matter to add bounds checking for both operator[] and pointer
dereferencing
– Objects in a vector can be stored in any kind of memory with the help of a
custom allocator
– Unlike standard arrays, vector have usable assignment and comparison
operators.

Vector Disadvantages

– Most implementations have to store a total of 3 memory pointers, compared to


one pointer for a standard C-style dynamically allocated array. This does use
up very much extra memory, so it is usually not a great burden.
– A vector will never release memory, even when the number of elements in the
vector is reduced.

Deque Advantages

– Since a deque acts a lot like a vector, it has the same advantages as using a
vector when compared to standard C-style arrays
– It can grow in either direction (front or back) equally well
– It is often faster than a vector when the container needs to grow to hold new
elements

Deque Disadvantages

– The operator[] is not as fast as vector's operator[], although it is still pretty fast
– Iterating over a deque is also slower than iterating over a vector

List Advantages

– Very fast element insertion/removal in the middle of the list


– Implements its own memory management system which actually can be helpful
on some platforms

List Disadvantages

– No random access iterator (which means no operator[])


– Uses extra memory to track next/previous node pointers (lists are best used for
large structure, not small data elements list a character)

General Guideline

Use a vector<> whenever possible since it has the lowest overhead and best
overall performance. However, if you are going to add and removing items from
the middle of the collection often, then consider using a list<>. Use a deque<>
whenever you will be inserting elements at the head or end most of the time, but
very seldom from the middle of the collection.

Container Adapters

The following containers are specialized containers that use one of the standard
containers to actually store the elements they manage. Basically they are
wrappers around one of the standard container templates that provide a restricted
set of operations.

Container Header Description


stack<T, <stack> or <stack.h> Implements a standard LIFO (Last-
Sequence> In, First-Out) container. You will
probably use the push() and pop()
members most often.
Queue<T, <queue> or <queue.h> Implements a standard FIFO (First-
Sequence> In, First-Out) container. This
container does not allow iteration.
You will probably use the push() and
top()/pop() members most often.
priority_queue <queue> or <stack.h> This container implements a FIFO,
with one small difference. The
largest element is always the first
item returned by the top() and pop()
methods.

Associative Containers

An associative containers stores objects based on key values.


Container Header Description
set<Key, Compare, <set> or <set.h> This container holds a unique
Alloc> collection of objects in sorted
sequence. The Compare
parameter defines the
function/functor to use for
comparing the objects (default is
less<Key>) and the Alloc
parameter is for a custom memory
allocator.
multiset<Key, <set> or <multiset.h> This container holds a collection
Compare, Alloc> of objects in sorted sequence.
Unlike a standard set<>, this type
of container allows duplicate keys.
map<Key, Data, <map> or <map.h> Similar to a set<> container,
Compare, Alloc> except the key is distinct from the
data being stored. Internally a
map stores pair<const Key, Data>
elements, organized by Key
values. The pair<> is a helper
template. All Key values must be
unique.
map<Key, Data, <map> or <multimap.h> Works like the standard map<>
Compare, Alloc> template, except duplicate Key
values are allowed.
Iterators
The standard template library makes heavy use of iterators, which basically acts
like pointers. They are used to indicate a position within a collection of elements
and are most often used to process a range of elements.

Iterator Categories

Iterator Category Description


Input Iterator This type of iterator allows you to read the element
it references. It does not allow you to change the
element.
Output Iterator This type of iterator grants permission to write an
element, but does not guarantee read access is
available (although it may allow reading the
element also.)
Forward Iterator A forward iterator generally supports both Input and
Output operations, unless the iterator is constant,
which restricts its usage to reading only. The
difference between a Forward iterator and an Input
or Output iterator is that Forward iterators can
usually be used with multi-pass algorithms.
Bidirectional Iterator This is very similar to a Forward iterator, except it
can be both incremented and decremented. Not all
of the container templates support Bidirectional
iterators.
Random Access Iterators This type of iterator supports incrementing,
decrementing and also adding and subtracting
arbitrary offsets, subscripting and more. They act
much more like traditional pointers than the other
iterators.

Concrete Iterator Template Classes

Iterator Class Description


istream_iterator<T,Distance> Reads objects of type T from an input stream
(such as cin). Stops when it reaches the end of
the stream. Used often with the copy()
algorithm.
ostream_iterator<T> Writes objects of type T to an output streams
(such as cout). Used often with the copy()
algorithm.
Iterator Class Description
reverse_iterator<RandomAcce This iterator reverses the meaning of the
ssIterator, T, Reference, increment (++) and decrement (--) operators.
Distance>
insert_iterator<Container> This iterator is used to insert objects into a
container. It will track of the next point of
insertion and advance automatically whenever a
new element is inserted.
front_insert_iterator<FronInsert This iterator class is an output iterator that
ionSequence> always inserts new elements at the front of the
container. The FrontInsertSequence means you
can only use this type of iterator with containers
that have the front(), push_front() and
pop_front() methods. Primarily this includes
the deque<> and list<> template classes.
back_insert_iterator<BackInser This iterator class is an output iterator that
tionSequence> always appends new elements at the end of a
container. The BackInsertionSequence means
you can only use this type of iterator with
containers that have the back(), push_back()
and pop_back() methods. Primarily this
includes the vector<>, list<> and deque<>
template classes.
Algorithms
The Standard Template Library also includes a large number of template functions
collectively referred to as algorithms. The combination of the container classes
with the algorithm template functions provides C++ with many advanced and
powerful constructs.

Algorithm Types

Algorithm Type Description


Non-mutating Algorithms in this category are used to process
and/or search a container, but never modify the
container's elements.
Mutating Algorithms in this category are used to modify
containers in some way.
Sorting There are a number of algorithms available for
sorting, searching and merging containers and their
elements.
Generalized Numeric These types of algorithms are used to perform some
kind of mathematical operation against elements in a
container.

Non-Mutating Algorithms

Remember, the non-mutating algorithms never modify the containers they are
working on.

Algorithm Description
UnaryFunction Iterates all of the elements from
first to last and calls function f
for_each( InputIterator first,
once per element. The return
InputIterator last, value is sometimes useful when
UnaryFunction f) dealing with functors.
InputIterator Attempts to locate value in the
elements pointed to by first and
find( InputIterator first,
last. The value is usually the
InputIterator last, same type as the elements in the
const EqualityComparable& value) container, but conversions are
performed if needed. Returns an
iterator that points to the first
match if found. Returns last if the
item cannot be found.
Algorithm Description
InputIterator Similar to the find() algorithm,
except instead of comparing
find_if(InputIterator first,
values directly, it passes each
InputIterator last, element in the range to a helper
Predicate pred) function (or functor) that tests the
object in some way and returns a
boolean value. If the helper
function returns true, the search
stops and an iterator to the
element is returned, otherwise last
is returned.
ForwardIterator This function iterates over the
container's elements to locate the
adjacent_find( ForwardIterator first,
first of 2 iterators that are valid.
ForwardIterator last) The first version is not very useful,
the second works like find_if() so
ForwardIterator
you can call a custom function (or
adjacent_find( ForwardIterator first, functor) that tests adjacent
ForwardIterator last, elements and returns a boolean.

BinaryPredicate binary_pred )
InputIterator Similar to using find(), except this
algorithm searches the first
find_first_of( InputIterator first1,
sequence to find any element that
InputIterator last1, is also in a second sequence.
ForwardIterator first2,
ForwardIterator last2) The second version of the function
allows you to use a custom
InputIterator
function (or functor) instead of the
find_first_of( InputIterator first1, standard operator==().
InputIterator last1,
ForwardIterator first2,
ForwardIterator last2,
BinaryPredicate comp)
Algorithm Description
iterator_traits<InputIterator>::difference_type This algorithm iterators over a
sequence and counts the number
count( InputIterator first,
of elements that match the given
InputIterator last, value.
const EqualityComparable& value)
void The first version returns the
number of matches found, while
count( InputIterator first,
the second version adds the
InputIterator last, number of matches to the value
const EqualityComparable& value, referenced by n.

Size& n )
The second version is deprecated
and may be removed later.
iterator_traits<InputIterator>::difference_type Similar to the count() algorithm,
but instead of comparing the
count_if( InputIterator first,
elements to some value, passes
InputIterator last, each element to a helper function
Predicate pred) (or functor) and only counts
elements where the helper
void function returns true.
count_if( InputIterator first,
InputIterator last, The second version is deprecated
Predicate pred, and may be removed later.

Size& n)
pair<InputIterator1, InputIterator2> Searches the sequence
references by first1 and last1 to
mismatch( InputIterator1 first1,
find an element that does not
InputIterator1 last1, match the elements in first2. In
InputIterator2 first2 ) other words, finds the first
difference between 2 containers.
pair<InputIterator1, InputIterator2>
mismatch( InputIterator1 first1,
The second versions of the
InputIterator1 last1, algorithm allows you to use a
InputIterator2 first2, custom function (or functor) to
compare the elements in the
BinaryPredicate binary_pred ) containers.
Algorithm Description
bool Similar to the mismatch()
algorithm, except this algorithm
equals( InputIterator first1,
simply returns true or false to
InputIterator last1, indicate whether the 2 sequences
InputIterator2 first2 ) are equal or not.

bool
Can also be done using:
equals( InputIterator first1,
mismatch(f1,l1,f2).first == l1
InputIterator last1,
InputIterator2 first2,
BinaryPredicate binary_pred )
ForwardIterator1 These algorithms attempt to find
the sequence first2->last2
search( ForwardIterator1 first1,
somewhere instead the sequence
ForwardIterator1 last1, first1->last1.
ForwardIterator2 first2,
ForwardIterator2 last2 ) This works a bit like searching for
a substring within a larger string,
ForwardIterator1
except of course the elements can
search( ForwardIterator1 first1, be of any type, not just characters.
ForwardIterator1 last1,
ForwardIterator2 first2,
ForwardIterator2 last2,
BinaryPredicate binary_pred )
ForwardIterator Attempts to find the position in the
sequence where value is repeated
search_n( ForwardIterator first,
count times in a row. Useful for
ForwardIterator last, testing for repeated elements.
Integer count,
const T& value ) NOTE: Using 0 for count will
always succeed, no matter the
ForwardIterator
value, since there will be no
search_n( ForwardIterator first, comparisons performed.
ForwardIterator last,
Integer count,
const T& value,
BinaryPredicate binary_pred )
Algorithm Description
ForwardIterator1 Works similar to search().
Probably should be named
find_end( ForwardIterator1 first1,
search_end().
ForwardIterator1 last1,
ForwardIterator2 first1,
Instead of returning the first match
ForwardIterator2 last2 ) in the search, this algorithm
returns an iterator that points to
ForwardIterator1
the last match instead.
find_end( ForwardIterator1 first1,
ForwardIterator1 last1,
ForwardIterator2 first2,
ForwardIterator2 last2,
BinaryPredicate binary_pred )

Mutating Algorithms

The mutating algorithms are used to make changes to containers or the elements
inside a container.

Algorithm Description
OutputIterator This algorithm copies the
elements referenced by first->last
copy( InputIterator first,
by overwriting the elements in
InputIterator last, result.
OutputIterator result ) NOTE; The output container must
be large enough to hold all the
copied elements, since this
algorithm assigns the copied
elements, it does not push them.
BidirectionalIterator2 Also copies the elements from
first->last into the container at
copy_backward( BidirectionalIterator1 first,
result, but copies from last to first
BidirectionalIterator1 last, in backward sequence.
BidirectionalIterator2 result )
NOTE: result must point to the
end of the sequence, not the
beginning.
void swap( Assignable& a, Assignable& b ) Assigns a to b and b to a.
Algorithm Description
void swap_iter( ForwardIterator1 a, Same as swap( *a, *b ).
ForwardIterator2 b )

ForwardIterator2 Swaps all the elements pointed to


by first1->last1 with the elements
swap_ranges( ForwardIterator1 first1,
pointed to by first2.
ForwardIterator2 last1,
ForwardIterator2 first2 )
OutputIterator This is similar to the copy()
algorithm, except before the
transform( InputIterator first,
elements are copied into the new
InputIterator last, container, a helper function (or
OutputIterator result, functor) is called that can change
(transform) the elements in some
UnaryFunction op ) way.
OutputIterator The second version allows you to
transform( InputIterator1 first1, do that same thing, except in this
case you are extracting elements
InputIterator1 last1, from 2 different containers and
InputIterator1 first2, combining them into one result
container, by calling a helper
OutputIterator result, function that receives one
BinaryFunction binary_op ) element from each input
container.
void Replaces every element with
value old_value, with the value
replace( ForwardIterator first,
new_value in the sequence first-
ForwardIterator last, >last.
const T& old_value,
const T& new_value )
void Similar to replace(), except
instead of comparing each input
replace_if( ForwardIterator first,
element against a value, calls a
ForwardIterator last, helper function (or functor). If the
Predicate pred, helper function returns true, the
element will be replaced by
const T& new_value ) new_value.
Algorithm Description
void Copies all the elements into a
new container, but replaces any
replace_copy( InputIterator first,
elements with old_value with
InputIterator last, new_value if found during the
OutputIterator result, copy process.

const T& old_value,


const T& new_value )
void Works like replace_copy(),
except only replaces elements
replace_copy_if( InputIterator first,
with new_value if the helper
InputIterator last, function (or functor) returns true.
OutputIterator result,
Predicate pred,
const T& new_value )
void Use this algorithm to quickly
assign value to the elements
fill( ForwardIterator first,
referenced by first->last.
ForwardIterator last,
const T& value )
OutputIterator This algorithm also assigns value
to the elements referenced by
fill_n( OutputIterator first,
first. It does this n times.
Size n,
const T& value )

void This algorithm calls the helper


function (or functor) gen and
generate( ForwardIterator first,
stores the results in each
ForwardIterator last, element referenced by first->last.
Generator gen )
void Calls the helper function (or
functor) gen and assigns the
generate_n( OutputIterator first,
results to the iterator first, exactly
Size n, n times.
Generator gen )
Algorithm Description
ForwardIterator Removes all elements with value
from the sequence referenced by
remove( ForwardIterator first,
first->last.
ForwardIterator last,
const T& value )
ForwardIterator Same as remove(), except calls
the helper function (or functor)
remove_if( ForwardIterator first,
pred to determine whether or not
ForwardIterator last, to remove the item. The helper
Predicate pred ) function returns true when the
element should be removed.
OutputIterator Copies elements in first->last to
result if they do not equal value.
remove_copy( InputIterator first,
InputIterator last,
OutputIterator result,
const T& value )
OutputIterator Calls the helper function (or
functor) pred for each element in
remove_copy_if( InputIterator first,
first->last and copies the element
InputIterator last, to result if pred returns false. In
OuputIterator result, other words, true elements are
not copied.
Predicate pred )
ForwardIterator Removes duplicate elements
from the sequence first->last so
unique( ForwardIterator first,
when completed, only unique
ForwardIterator last ) elements remain. The second
flavor uses a helper function (or
ForwardIterator
functor) to decide if elements are
unique( ForwardIterator first, unique or not.
ForwardIterator last,
BinaryPredicate binary_pred )
Algorithm Description
OutputIterator Copies only unique elements
(skips consecutive duplicates)
unique_copy( InputIterator first,
from first->last into result. Works
InputIterator last, best when the input container is
OutputIterator result ) sorted.

OutputIterator
unique_copy( InputIterator first,
InputIterator last,
OutputIterator result,
BinaryPredicate binary_pred )
void Reverses a container so the last
element becomes the first and
reverse( BidirectionalIterator first,
the first element becomes the
BidirectionalIterator last ) last and so on.
OutputIterator Copies elements first->last into
container result, in reverse
reverse_copy( BidirectionalIterator first,
sequence.
BidirectionalIterator last,
OutputIterator result )
ForwardIterator Rearranges the container so
middle becomes first and last
rotate( ForwardIterator first,
becomes middle. This means
ForwardIterator last, first also becomes middle+1.
ForwardIterator middle ) Acts like rotating a circle.
OutputIterator Works like rotate(), except
copies the rotated elements into
rotate_copy( ForwardIterator first,
result. Faster then doing a copy
ForwardIterator middle, () followed by a rotate().
ForwardIterator last,
OutputIterator result )
void Randomly rearranges all the
random_shuffle( RandomAccessIterator first, elements in first->last. The
second version allows you to use
RandomAccessIterator last ) a custom random number
generator functor.
void
random_shuffle( RandomAccessIterator first,
RandomAccessIterator last,
RandomNumberGenerator& rand )
Algorithm Description
RandomAccessIterator Works like the random_shuffle()
algorithm, except instead of
random_sample( InputIterator first,
rearranging the input container,
InputIterator last, copies the elements randomly
RandomAccessIterator ofirst, into another container. Each
input element will only appear
RandomAccessIterator olast ) once in the output, in random
RandomAccessIterator sequence.

random_sample( InputIterator first,


InputIterator last, Again a custom random number
generator can be used if needed.
RandomAccessIterator ofirst,
RandomAccessIterator olast,
RandomNumberGenerator& rand )
OutputIterator Similar to random_sample(),
except this algorithm stops after
random_sample_n( ForwardIterator first,
copying n elements. This
ForwardIterator last, algorithm preserves the relative
OutputIterator out, order of the copied elements.

Distance n )
OutputIterator
random_sample_n( ForwardIterator first,
ForwardIterator last,
OutputIterator out,
Distance n,
RandomNumberGenerator& rand )
ForwardIterator This algorithm rearranges the
elements in first->last by calling
partition( ForwardIterator first,
the helper function (or functor)
ForwardIterator last, pred against each element. All
Predicate pred ) elements where pred returns true
are placed before the elements
that return false. The returned
iterator will point to the middle.
(i.e. The first false element.)
Algorithm Description
ForwardIterator Same as partition(), except the
elements will maintain their
stable_partition( ForwardIterator first,
relative order within the
ForwardIterator last, sequence.
Predicate pred )

Sorting Algorithms

This group of algorithm are used to fully or partially sort the elements in a
container.

Algorithm Description
void Rearranges the container so the
elements are in sorted sequence.
sort( RandomAccessIterator first,
By default, it uses operator<() to
RandomAccessIterator last ) compare elements.
void
sort( RandomAccessIterator first, The second version allows you to
use a helper function (or function)
RandomAccessIterator last,
to get custom sort sequences.
Compare comp )
void Also sorts elements in a
container, but unlike the standard
stable_sort( RandomAccessIterator first,
sort(), this one preserves the
RandomAccessIterator last ) relative order of duplicate
elements. This means that
void
stable_sort() is less efficient
stable_sort( RandomAccessIterator first, than standard sort().
RandomAccessIterator last,
Compare comp )
Algorithm Description
void This algorithm also sorts
elements in containers, but in this
partial_sort( RandomAccessIterator first,
case only elements from first-
RandomAccessIterator middle, >middle are sorted and placed at
RandomAccessIterator last ) the beginning of the container.
The elements from middle->last
void are unsorted (and probably
partial_sort( RandomAccessIterator first, rearranged).

RandomAccessIterator middle,
RandomAccessIterator last,
Compare comp )
RandomAccessIterator This algorithm combines partial
sorting with copying of the
partial_sort_copy( InputIterator first,
elements. It will stop whenever it
InputIterator last, processes (last-first) or
RandomAccessIterator result_first, (result_last-result_first) elements,
whichever is smaller.
RandomAccessIterator result_last )
RandomAccessIterator
Useful for extracting X number of
partial_sort_copy( InputIterator first, items (perhaps the smallest or
InputIterator last, largest values) from a large
container into a smaller one.
RandomAccessIterator result_first,
RandomAccessIterator result_last,
Compare comp )
bool Returns true if the range is
already sorted, false otherwise.
is_sorted( ForwardIterator first,
ForwardIterator last )
bool
is_sorted( ForwardIterator first,
ForwardIterator last,
Compare comp )
Algorithm Description
void This is a special kind of partial
sort that ensures elements to the
nth_element( RandomAccessIterator first,
left of nth are less than all
RanomAccessIterator nth, elements to the right of nth. The
RandomAccessIterator last ) left side may or may not be
sorted. The same applies to the
void right side. However, all items to
nth_element( RandomAccessIterator first, the left will be less than the items
to the right, with nth used as a
RandomAccessIterator nth, split point.
RandomAccessIterator last,
Compare comp )

Searching Algorithms

Algorithm Description
ForwardIterator This algorithm performs a fast
binary search of a sorted
lower_bound( ForwardIterator first,
container and returns the iterator
ForwardIterator last, where a new element of value
const T& value ) can be inserted to maintain the
proper order of elements.
ForwardIterator
Uses operator<() by default, but
lower_bound( ForwardIterator first, the second version can be used
ForwardIterator last, to customize the comparison.

const T& value, NOTE: The first version requires


value to be comparable with a T.
Compare comp )
ForwardIterator This algorithm also performs a
fast binary search of a sorted
upper_bound( ForwardIterator first,
container. The difference is in the
ForwardIterator last, returned iterator. This one
const T& value ) returns a reference to the first
element greater than value.
ForwardIterator
By comparison the lower_bound
upper_bound( ForwardIterator first, () algorithm returns a reference to
ForwardIterator last, the first element greater than or
equal to value.
const T& value,
Compare comp )
Algorithm Description
pair<ForwardIterator, ForwardIterator> Combines using lower_bound()
and upper_bound() into a single
equal_range( ForwardIterator first,
algorithm that returns both
ForwardIterator last, iterators in a single function call.
const T& value ) NOTE: The first version only
requires that value be
pair<ForwardIterator, ForwardIterator>
comparable to elements of type
equal_range( ForwardIterator first, T.
ForwardIterator last,
const T& value,
Compare comp )
bool Compares each element in first-
>last against value using either
binary_search( ForwardIterator first,
the default comparison operator
ForwardIterator last, or a custom comparison function
const T& value ) (or functor) comp and returns
true if found, false otherwise.
bool
NOTE: Since you will often need
binary_search( ForwardIterator first, to know the position of the
ForwardIterator last, element, most of the time you
should consider using
const T& value, lower_bound(), upper_bound(),
Compare comp ) or equal_range() instead.

Merging Algorithms

There are a couple of algorithms you can use for combining and merging sorted
containers together.
Algorithm Description
OutputIterator Combines 2 sorted containers
(first1->last1 and first2->last2)
merge( InputIterator1 first1,
into another container (result) so
InputIterator1 last1, that the output container is also
InputIterator2 first2, sorted. The merge is stable,
which means the relative order of
InputIterator2 last2, duplicate elements is preserved.
OutputIterator result )
OutputIterator
merge( InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result,
Compare comp )
void This algorithm takes a container
that has been partially sorted
inplace_merge( BidirectionalIterator first,
(split around middle) and
BidirectionalIterator middle, completes the sort so the entire
BidirectionalIterator last ) container is now sorted.

void
inplace_merge( BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last,
Compare comp )

Set Algorithms

There are also a set of algorithms designed specifically for performing set
operations. Most of these algorithms do not require a set<> container, but they
may be used to implement the set<> template class.
Algorithm Description
bool Tests 2 sorted ranges to
determine if all of the elements in
includes( InputIterator1 first1,
first2->last2 are also found in
InputIterator1 last1, first1->last1. Returns true only if
InputIterator2 first2, all of the elements in the second
container can be found in the first
InputIterator2 last2 ) container.
bool Both input containers must be
includes( InputIterator1 first1, sorted for this algorithm to work
properly.
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
Compare comp )
OutputIterator Copies all the sorted elements
that are in either first1->last1 or
set_union( InputIterator1 first1,
first2->last2 into a new container
InputIterator1 last1, (result), while preserving the sort
InputIterator2 first2, sequence.

InputIterator2 last2, Both input containers must be


sorted for this algorithm to work
OutputIterator result ) properly.
OutputIterator NOTE: If the same value
set_union( InputIterator1 first1, elements appear in both
containers, then this algorithm
InputIterator1 last1, copies the elements from the
InputIterator2 first2, container where the value is
repeated the most often.
InputIterator2 last2,
OutputIterator result,
Compare comp )
Algorithm Description
OutputIterator Copies all the sorted elements
that are found in both first1-
set_intersection( InputIterator1 first1,
>last1 and first2->last2 into a
InputIterator1 last1, new container (result), while
InputIterator2 first2, preserving the sort sequence.

InputIterator2 last2, Both input containers must be


sorted for this algorithm to work
OutputIterator result ) properly.
OutputIterator NOTE: If the same value
set_intersect( InputIterator1 first1, elements appear in both
containers, then this algorithm
InputIterator1 last1, copies the elements from the
InputIterator2 first2, container where the value is
repeated the least often.
InputIterator2 last2,
OutputIterator result,
Compare comp )
OutputIterator Copies all the sorted elements
that are in first1->last1 but are
set_difference( InputIterator1 first1,
not in first2->last2 into a new
InputIterator1 last1, container (result), preserving the
InputIterator2 first2, sort sequence.

InputIterator2 last2, Both input containers must be


sorted for this algorithm to work
OutputIterator result ) properly.
OutputIterator
set_difference( InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result,
Compare comp )
Algorithm Description
OutputIterator Copies all the sorted elements
that are in first1->last1 but not in
set_symmetric_difference(
first2->last2 as well as all the
InputIterator1 first1, element in first2->last2 that are
InputIterator1 last1, not in first1->last1 into a new
container (result), preserving the
InputIterator2 first2, sort sequence. After using this
InputIterator2 last2, algorithm the output container will
have the set of elements that are
OutputIterator result ) not found in both input
OutputIterator containers.
set_symmetric_difference( Both input containers must be
sorted for this algorithm to work
InputIterator1 first1, properly.
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result,
Compare comp )

Heap Operations

A heap is data structure similar to a tree, but normally stores its elements as an
array (including vector and deque). The difference is that in a heap not every
element has to be perfectly sorted. Instead the elements have to arranged so the
highest value is always above the lower values. This is used by the
priority_queue<> template internally to arrange elements by value.

Algorithm Description
Void Turns the container first->last into a
heap. Typically the underlying
make_heap( RandomAccessIterator first,
container will be a C-style array,
RandomAccessIterator last) vector<> or deque<> object.
void
make_heap( RandomAccessIterator first,
RandomAccessIterator last,
Compare comp )
Algorithm Description
void This function moves an element
that has already been added to the
push_heap( RandomAccessIterator first,
end of a container into its proper
RandomAccessIterator last ) location within the heap structure.
You must add the element to the
void
underlying container yourself,
push_heap( RandomAccessIterator first, perhaps by using the push_back()
RandomAccessIterator last, function.

Compare comp )
void This method removes the largest
element from the heap structure
pop_heap( RandomAccessIterator first,
(the largest element is normally the
RandomAccessIterator last ) first element). It does not actually
remove the element, but instead
void
moves it to the end of the
pop_heap( RandomAccessIterator first, underlying container and
RandomAccessIterator last, reorganizes the remaining
elements so the heap is still valid.
Compare comp )
void Returns the heap's underlying
heap sequence back into a sorted
sort_heap( RandomAccessIterator first,
sequence. The relative order of
RandomAccessIterator last ) the elements is not guaranteed to
be preserved.
void
sort_heap( RandomAccessIterator first,
RandomAccessIterator last,
Compare comp )
bool Tests a container to determine if it
is already organized into the
is_heap( RandomAccessIterator first,
sequence needed to be treated as
RandomAccessIterator last ) a heap structure.
bool
is_heap( RandomAccessIterator first,
RandomAccessIterator last,
Compare comp )

Miscellaneous Algorithms

Here are several general-purpose algorithms.


Algorithm Description
const T& Compares a to b and returns the
one with the lesser value (returns a
min( const T& a,
if they are equal). Uses operator<
const T& b ) by default.
const T&
min( const T& a,
const T& b,
Compare comp )
const T& Compares a to b and returns the
one with the greater value (returns
max( const T& a,
a if they are equal). Uses
const T& b ) operator< by default.
const T&
max( const T& a,
const T& b,
Compare comp )
ForwardIterator Finds the smallest element in the
container and returns an iterator
min_element( ForwardIterator first,
that references that element.
ForwardIterator1 last )
ForwardIterator
min_element( ForwardIterator first,
ForwardIterator last,
Compare comp )
ForwardIterator Finds the largest element in the
container and returns an iterator
max_element( ForwardIterator first,
that references that element.
ForwardIterator1 last )
ForwardIterator
max_element( ForwardIterator first,
ForwardIterator last,
Compare comp )
Algorithm Description
bool While this algorithm's name is
awkward, the job it performs is
lexicographical_compare(
simple. It compares elements one
InputIterator1 first1, by one from both containers until it
InputIterator1 last1, either reaches the end or finds
elements that do not match. If both
InputIterator2 first2, containers stored exactly the same
InputIterator2 last2 ) elements in the same sequence, it
returns true, otherwise it returns
bool false.
lexicographical_compare(
InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
Compare comp )
bool This algorithm is used to rearrange
next_permutation( BidirectionalIterator first, the elements in a sorted container
in every other possible sequence
BidirectionalIterator last ) (or permutation). Every time you
call this algorithm, the elements will
bool
be reordered and it will return true.
next_permutation( BidirectionalIterator first, Once all the permutations have
BidirectionalIterator last, been generated, the elements are
returned to the original sorted
Compare comp ) sequence and false is returned.
bool This algorithm is the mirror image
prev_permutation( BidirectionalIterator first, of next_permutation().
BidirectionalIterator last )
bool
prev_permutation( BidirectionalIterator first,
BidirectionalIterator last,
Compare comp )
Algorithm Description
T Adds all the elements from first-
>last to init and returns the sum.
accumulate( InputIterator first,
The second version allows you to
InputIterator last,
use a function (or functor) that will
T init ) be called with the previous result
(initially the same as init) and the
T
next element in the container. The
accumulate( InputIterator first, function will return a value of type T
InputIterator last, that will be added to the next
result.
T init,
NOTE: Defined in the header
BinaryFunction binary_op ) <numeric>.
T This algorithm takes each element
in the first container (first1->last1)
inner_product( InputIterator1 first1,
and multiplies it by each
InputIterator1 last1, corresponding element in the
InputIterator2 first2, second container (first2) and
returns the sum of all of the results
T init ) + the value in init. Think of it as a
T crude matrix multiply and add
operation.
inner_product( InputIterator1 first1,
NOTE: Defined in the header
InputIterator1 last1, <numeric>.
InputIterator2 first1,
T init,
BinaryFunction1 binary_op1,
BinaryFunction2 binary_op2 )
OutputIterator This algorithm visits each element
in a container and adds the
partial_sum( InputIterator first,
element's value to the next
InputIterator last, element's value and stores the
OutputIterator result ) result in the output container. The
first element is always just copied
OutputIterator to the output.
partial_sum( InputIterator first,
InputIterator last, Output[0] = Input[0]
OutputIterator result, Output[i] = Input[i-1] + Input[i]
BinaryOperator binary_op )
Algorithm Description
OutputIterator Copies the first element from first
to result. Next, subtracts all
adjacent_difference( InputIterator first,
elements from the previous
InputIterator last, element and stores the result in
OutputIterator result ) result.

OutputIterator
Output[0] = Input[0]
adjacent_difference( InputIterator first,
Output[i] = Input[i] – Input[i-1]
InputIterator last,
OutputIterator result )
Function Objects (aka Functors)
A function object or functor is any object that can be used as if it were a plain old
function. A class can used as a functor if it defines operator(), which is
sometimes referred to as the default operator. So a functor is really either a
pointer to a static function, or a pointer to an object that defines operator(). The
advantages of using a function object should become apparent soon.

Many of the algorithms in the Standard Template Library will accept a functor to
use instead of the default functor defined by the template class. This allows the
user of the algorithm to adapt the algorithm to their specific needs. You can use
the predefined function objects that are included with the STL, or you can roll your
own as long as your functors have the required function signatures.

There are 3 major types of function objects and several other less commonly used
function objects.

Major Functor Types

Functor Type Used By Description


Predicate (Unary Unary: remove_if, find_if, A predicate function object
or Binary) count_if, replace_if, returns a bool value of true
replace_copy_if, remove_if, and or false. Generally they will
remove_copy_if receive one argument of
type T, but some algorithms
Binary: adjacent_find,
will require a binary
find_first_of, mismatch, equal,
predicate function which
search, search_n, find_end,
takes in two arguments of
unique, and unique_copy
type T and returns a bool.
Comparison sort, stable_sort, partial_sort, This kind of function object
Functions partial_sort_copy, is_sorted, takes two arguments of type
nth_element, lower_bound, T and return true or false
upper_bound, equal_range, after the items have been
binary_search, merge, compared. The operator<
inplace_merge, includes, is an example of this kind of
set_union, set_intersection, function and is generally the
set_difference, default used when you do
set_symmetric_difference, not supply your own
make_heap, push_heap, function object.
pop_heap, sort_heap, is_heap,
min, max, min_element,
max_element,
lexicographical_compare,
next_permutation and
prev_permutation
Functor Type Used By Description
Numeric Unary: for_each and transform This kind of function will
Functions (Unary Binary: transform, accumulate, generally accept either one
or Binary) or two arguments of type T
and inner_product
and returns the results of
some sort of mathematical
operation. The accumulate
algorithm uses operator+
as its default numeric
function.

Here is an example of an algorithm that uses a function.

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

using namespace std;

bool failingGrade( int score )


{
return score < 70;
}

int main( int argc, char *argv[] )


{
vector<int> scores;

scores.push_back( 69 );
scores.push_back( 70 );
scores.push_back( 85 );
scores.push_back( 80 );

cout << “Scores Before: “ << endl;


copy( scores.begin(), scores.end(), ostream_iterator<int>(cout,
“\n”) );

vector<int>::iterator new_end;

new_end = remove_if( scores.begin(), scores.end(), failingGrade );


scores.remove( new_end, scores.end() );

cout << “Scores After: “ << endl


copy( scores.begin(), scores.end(), ostream_iterator<int>(cout,
“\n”) );

return 0;
}

The only problem with this example is that the failingGrade function is not very
flexible. It uses a hard-coded cutoff of 70.
Here is a better version that uses a function object (object of a class with an
operator() defined).

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

using namespace std;

class Failing
{
private:
int cutoff;
public:
Failing( int below ) : cutoff(below) {}
bool operator()( int score )
{
return score < cutoff;
}
};

int main( int argc, char *argv[] )


{
vector<int> scores;

scores.push_back( 69 );
scores.push_back( 70 );
scores.push_back( 85 );
scores.push_back( 80 );

cout << "Scores Before: " << endl;


copy( scores.begin(), scores.end(), ostream_iterator<int>(cout,
"\n") );

vector<int>::iterator new_end;
new_end = remove_if( scores.begin(), scores.end(), Failing(75) );
scores.erase( new_end, scores.end() );

cout << "Scores After: " << endl;


copy( scores.begin(), scores.end(), ostream_iterator<int>(cout,
"\n") );

return 0;
}

This can also be achieved using a class template instead as follows:

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

using namespace std;

template <typename T>


class Failing
{
private:
T cutoff;
public:
Failing( T below ) : cutoff(below) {}
bool operator()( T const& score )
{
return score < cutoff;
}
};

int main( int argc, char *argv[] )


{
vector<int> scores;

scores.push_back( 69 );
scores.push_back( 70 );
scores.push_back( 85 );
scores.push_back( 80 );

cout << "Scores Before: " << endl;


copy( scores.begin(), scores.end(), ostream_iterator<int>(cout,
"\n") );

vector<int>::iterator new_end;
new_end = remove_if( scores.begin(), scores.end(), Failing<int>
(81) );
scores.erase( new_end, scores.end() );

cout << "Scores After: " << endl;


copy( scores.begin(), scores.end(), ostream_iterator<int>(cout,
"\n") );

return 0;
}
Predefined Function Objects
Since using function objects with algorithms is so common, a number of
predefined function objects are available for you to use in your code.

Arithmetic Function Objects

Functor Type Description


plus<T> Binary Adds two elements together to calculate a
sum.
minus<T> Binary Subtracts two elements to calculate the
difference.
multiplies<T>* Binary Multiples two elements to calculate a
* times<T> in older product.
versions of STL
divides<T> Binary Divides one element by another to calculate
a dividend.
modulus<T> Binary Performs a modulo operation against two
elements and calculates the remainder.
negate<T> Unary Negates the element so positive values
become negative and vice-versa.

Comparison Function Objects

Functor Type Description


equal_to<T> Binary Compares two elements for equality using
operator==.
not_equal_to<T> Binary Compares two elements for inequality using
operator==.
less<T> Binary Compares two elements using operator<.
greater<T> Binary Compares two elements using operator>.
less_equal<T> Binary Compares two elements using operator<=.
greater_equal<T> Binary Compares two elements using operator>=.

Logical Function Objects

Functor Type Description


logical_and<T> Binary Performs an AND operation with two other
conditions.
Functor Type Description
logical_or<T> Binary Performs an OR operation with two other
conditions.
logical_not<T> Unary Inverts boolean logic.

Function Object Adapters


Alas the function objects listed above are quite useful, but limited in scope. There
is no apparent way you can use functors like less<T> with any algorithm that
requires a unary function, or is there?

This is the concept of a Function Object Adapter. They can be used to convert
binary functors into unary functors or to do other conversions such as converting a
plain function into a function object or converting a class member function back
into a standard function so it can be used with the algorithms.

Adapter Description Notes


binder1st Adapts a unary Don't use directly. Instead
function/functor and a use the bind1st() function,
constant into a binary which creates a binder1st
functor, where the constant object internally.
will be used as the first
argument to the functor.
binder2nd Adapts a unary Don't use directly. Instead,
function/functor and a use the bind2nd() function,
constant into a binary which creates a binder2nd
functor, where the constant object internally.
will be used as the second
argument to the functor.
ptr_fun Converts a pointer to a Can be used to convert both
standard function into a unary and binary functions
function object. Needed into function objects.
when trying to customize
the container templates
(such as set<>) which
require a functor class and
do not support function
objects.
unary_negate Converts a unary predicate Don't use directly. Use the
function object by inverting not1() function instead.
the logical return value.
binary_negate Converts a binary predicate Don't use directly. Use the
function object by inverting not2() helper function
the logical return value. instead.
Adapter Description Notes
unary_compose Combines multiple function Don't use directly. Use the
objects into a single object compose1() helper function
by calling the first function instead.
and passing the results to
the next function. In other
words, allows you to chain
function calls together.
binary_compose Combines multiple function Don't use directly. Use the
objects into a single object compose2() helper function
in the same manner as instead.
unary_compose, except
works on binary functions.
mem_fun Converts a member Use this helper function
function of a class (or when you are storing
struct) into a plain function pointers to objects in a
so it can be used with container and want to call a
algorithms. It performs member function of the class
opposite from the same in an algorithm.
way ptr_fun() does.
mem_fun_ref Converts a member Use this helper function
function of a class (or when you are storing objects
template) into a function (not pointers) in a container
object just like the and need to access the
mem_fun() function object by reference.
adapter does.

You might also like