1. Introduction to C++ STL
CodeClass[5]
Disclaimer: Slides taken from various sources and modified as required
2. C++ Generic Programming: Templates
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
Output:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
2
3. STL – Standard Template Library
Collections of useful classes for common data
structures
Ability to store objects of any type (template)
Study of containers
Containers form the basis for treatment of data
structures
Container – class that stores a collection of data
STL consists of 10 container classes:
Sequence containers
Adapter containers
Associative containers
3
4. Why use STL?
STL offers an assortment of containers
STL publicizes the time and storage complexity of its
containers
STL containers grow and shrink in size automatically
STL provides built-in algorithms for processing containers
STL provides iterators that make the containers and
algorithms flexible and efficient.
STL is extensible which means that users can add new
containers and new algorithms such that:
STL algorithms can process STL containers as well as user defined
containers
User defined algorithms can process STL containers as well user
defined containers
4
5. Standard Template Library
The standard template library (STL) contains
Containers
Algorithms
Iterators
A container is a way that stored data is organized in
memory, for example an array of elements.
Algorithms in the STL are procedures that are applied to
containers to process their data, for example search for an
element in an array, or sort an array.
Iterators are a generalization of the concept of pointers,
they point to elements in a container, for example you can
increment an iterator to point to the next element in an
array
5
6. Strings
In C we used char * to represent a string.
The C++ standard library provides a common
implementation of a string class abstraction
named string.
6
11. string length
The length of string is returned by its
size() operation.
#include <string>
string str = “something”;
cout << “The size of “
<< str
<< “is “ << str.size()
<< “characters.” << endl;
11
12. The size method
str.size() ???
In C we had structs containing only data, In
C++, we have :
class string
{
…
public:
…
unsigned int size();
…
};
12
13. String concatenation
concatenating one string to another is done
by the ‘+’ operator.
string str1 = “Here ”;
string str2 = “comes the sun”;
string concat_str = str1 + str2;
13
14. String comparison
To check if two strings are equal use
the ‘==‘ operator.
string str1 = “Here ”;
string str2 = “comes the sun”;
if ( str1 == str2 )
/* do something */
else
/* do something else */
14
15. String assignment
To assign one string to another
use the “=“ operator.
string str1 = “Sgt. Pappers”;
string str2 = “lonely hearts club bend”;
str2 = str1;
Now : str2 equals “Sgt. Pappers”
15
17. Containers
A container is a way to store data, either built-in data
types like int and float, or class objects
The STL provides several basic kinds of containers
<vector> : one-dimensional array (similar to C array, but dynamic)
<list> : double linked list
<deque> : double-ended queue
<queue> : queue
<stack> : stack
<set> : set of ordered keys
<map> : associative array (set of ordered key/value pairs)
17
18. Sequence Containers
A sequence container stores a set of elements in sequence, in
other words each element (except for the first and last one) is
preceded by one specific element and followed by another,
<vector>, <list> and <deque> are sequential containers
In an ordinary C++ array the size is fixed and can not change
during run-time, it is also tedious to insert or delete elements.
Advantage: quick random access
<vector> is an expandable array that can shrink or grow in size,
but still has the disadvantage of inserting or deleting elements
in the middle
Vector should be your default choice, but choose wisely
Backward compatible with C : &v[0] points to the first element
18
19. Sequence Containers
<list> is a ’traditional’ double linked list (each element
has points to its successor and predecessor), it is
quick to insert or delete elements but has v.slow
random access
<deque> is a double-ended queue, that means one
can insert and delete elements from both ends, it is a
kind of combination between a stack (last in first out)
and a queue (first in first out) and constitutes a
compromise between a <vector> and a <list>
Offers random access, back and front insertion but
slower than vectors, no C compatibilty
19
20. Associative Containers
An associative container is non-sequential but uses
a key to access elements. The keys, typically a
number or a string, are used by the container to
arrange the stored elements in a specific order,
for example in a dictionary the entries are ordered
alphabetically.
Offers O(log n) insertion and access
20
21. Associative Containers
A <set> stores a number of items which contain keys. The
keys are the attributes used to order the items, for
example a set might store objects of the class. People
which are ordered alphabetically using their name
A <map> stores pairs of objects: a key object and an
associated value object. A <map> is somehow similar to an
array except instead of accessing its elements with index
numbers, you access them with indices of an arbitrary
type.
<set> and <map> only allow one key of each value,
whereas <multiset> and <multimap> allow multiple
identical key values 21
22. Defining a new vector
Header file: <vector>
Syntax: vector<of what>
For example :
vector<int> - vector of integers.
vector<string> - vector of strings.
vector<int * > - vector of pointers to integers.
vector<Shape> - vector of Shape objects. Shape is a
user defined class.
Two ways to use vector type: Array style, and STL style
22
25. Vector Container
vector<int> v(3); // create a vector of ints of size 3
v[0]=23;
v[1]=12;
v[2]=9; // vector full
v.push_back(17); // put a new value at the end of array
for (int i=0; i<v.size(); i++) //member function size() of vector
printf(”%d ”,v[i]); // random access to i-th element
25
26. Vector Container
#include <vector>
#include <cstdio>
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int> v(arr, arr+4); // initialize vector with C array
while ( ! v.empty()) // until vector is empty
{
printf(”%d ”, v.back() ); // output last element of vector
v.pop_back(); // delete the last element
}
26
27. Tip : vector<bool>
Meyers: "As an STL container, there are really only two
things wrong with vector<bool>. First it's not an STL
containers. Second it doesn't hold bools. Other than
that, there's not much to object to." (Effective STL, p79)
vector<bool> does not conform to STL requirements
it stores bools in a packed representation (e.g. bitfield)
Accessing it returns proxy objects to bools, not true
bools
Use a deque<bool> or a bitset to store bools
You won't get C compatibility (but C doesn't have bools
anyways)
27
28. Tip : reserve()
Inserting elements may cause a memory
reallocation
container is doubled in capacity
elements are copied over
Both string and vector let you increase capacity in
advance through reserve()
May eliminate unnecessary reallocations
Keeps safety of dynamic data structures over C arrays
v.reserve(n)allocates memory for n objects
Distinguish capacity (memory) and size (objects)
Writing beyond the size of the container is still bad
28
29. Tip : size() and empty()
You may check whether a container is empty by
writing c.size() == 0 or c.empty()
However, with lists, which have a splice() function,
if splice() is O(1), size() must be O(n) and
conversely.
Therefore, while empty() will always run in O(1),
size() may not. You should thus prefer calling
empty() to checking size() against zero.
29
30. vector<int>
array_
Iterators
Iterators are pointer-like entities that are used to access
individual elements in a container.
Often they are used to move sequentially from element to
element, a process called iterating through a container.
17
4
23
12
size_ 4
vector<int>::iterator
The iterator corresponding to
the class vector<int> is of
the type vector<int>::iterator
30
31. Iterators
The member functions begin() and end() return an
iterator to the first and past the last element of a
container
vector<int> v
array_ 17
4
23
12
size_ 4
v.end()
v.begin()
31
32. Iterators
One can have multiple iterators pointing to different or
identical elements in the container
vector<int> v
array_ 17
4
23
12
size_ 4
i3
i1
i2
32
33. Common Iterator Operations
* Return the item that the iterator currently references
++ Move the iterator to the next item in the list
-- Move the iterator to the previous item in the list
== Compare two iterators for equality
!= Compare two iterators for inequality
33
34. Iterators
#include <vector>
#include <cstdio>
using namespace std;
int main
{
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int> v(arr, arr+4); //initialize vector with C array
vector<int>::iterator iter=v.begin(); //iterator for class vector
// define iterator for vector and point it to first element of v
printf(”First element of v = %dn”,*iter); // de-reference iter
iter++; // move iterator to next element
iter=v.end()-1; // move iterator to last element
}
34
35. Iterators
int max(vector<int>::iterator start, vector<int>::iterator end)
{
int m=*start;
while(start != end)
{
if (*start > m)
m=*start;
++start;
}
return m;
}
printf(”max of v = %d”, max(v.begin(),v.end())); 35
36. Iterators
vector<int> v;
for(int i=0;i<n;i++)
{
scanf(”%d”,&num);
v.push_back(num);
}
for (vector<int>::iterator i=v.begin(); i!=v.end(); i++)
// initialize i with pointer to first element of v
// i++ increment iterator, move iterator to next element
{
printf(”%d ”,*i); // de-referencing iterator returns the
// value of the element the iterator points at
}
for(i=0;i<n;i++)
printf(”%d ”,v[i]);
36
37. Container Adaptors
There are a few classes acting as wrappers around
other containers, adapting them to a specific
interface
stack – ordinary LIFO
queue – single-ended FIFO
priority_queue – the sorting criterion can be specified
• They are implemented using the containers seen before
- They do not provide actual data structure
• Container adapters do not support iterators
• The functions push and pop are common to all
container adapters 37
38. Stack Container
They are implemented with vector, list, and deque
(by default)
These containers restrict how elements enter and
leave a sequence
Stack
allows access at only one end of the sequence (top)
Adds objects to container by pushing the object onto
the stack
Removes objects from container by popping the stack
LIFO ordering (last end, first out)
Header file: <stack>
• Example of creating stacks
- A stack of int using a vector: stack < int, vector < int > > s1;
- A stack of int using a list: stack < int, list < int > > s2;
- A stack of int using a deque: stack < int > s3; 38
39. Queue Container
Queue
Allows access only at the front and rear of the sequence
Items enter at the rear and exit from the front
Example: waiting line at a grocery store
FIFO ordering (first-in first-out )
push(add object to a queue)
pop (remove object from queue)
• Implemented with list and deque (by default)
• Header file <queue>
• Example:
- A queue of int using a list: queue <int, list<int>> q1;
- A queue of int using a deque: queue <int> q2;
39
40. Priority Queue Container
Priority queue
Operations are similar to those of a stack or queue
Elements can enter the priority queue in any order
Once in the container, a delete operation removes the
largest (or smallest) value
Example: a filtering system that takes in elements and
then releases them in priority order
8
18 13
3 15
27
40
41. Priority Queue Container
• Priority Queues are implemented with vector (by
default) or deque
• The elements with the highest priority are removed
first
- less<T> is used by default for comparing elements
• Header file <queue>
41
42. Associative Containers
In an associative container the items are not arranged
in sequence, but usually as a tree structure or a hash
table.
The main advantage of associative containers is the
speed of searching (binary search like in a dictionary)
Searching is done using a key which is usually a single
value like a number or string
The value is an attribute of the objects in the container
The STL contains two basic associative containers
sets and multisets
maps and multimaps
42
43. • Associative containers use keys to store and retrieve
elements
• There are four types: multiset, set, multimap and
map
- all associative containers maintain keys in sorted order
- all associative containers support bidirectional iterators
- set does not allow duplicate keys
- multiset and multimap allow duplicate keys
- multimap and map allow keys and values to be mapped
Associative Containers
43
44. Set Container
Set
Collection of unique values, called keys or set members
Contains operations that allow a programmer to:
determine whether an item is a member of the set
insert and delete items very efficiently
5 1 3
6 27 15
Buick Ford
Jeep BMW
Set A Set B
44
45. Associative Containers: multiset
• Multisets are implemented using a red-black binary
search tree for fast storage and retrieval of keys
• Multisets allow duplicate keys
• The ordering of the keys is determined by the STL
comparator function object less<T>
• Keys sorted with less<T> must support comparison
using the < operator
45
46. Sets and Multisets
#include <set>
string names[] = {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”};
set<string, less<string> > nameSet(names,names+5);
// create a set of names in which elements are alphabetically
// ordered string is the key and the object itself
nameSet.insert(”Patric”); // inserts more names
nameSet.insert(”Maria”);
nameSet.erase(”Juan”); // removes an element
set<string, less<string> >::iterator iter; // set iterator
string searchname;
cin >> searchname;
iter=nameSet.find(searchname); // find matching name in set
if (iter == nameSet.end()) // check if iterator points to end of set
printf(”%d not in set!”,searchname);
else
printf(”%d is in set!”,searchname); 46
47. Set and Multisets
string names[] = {”Ole”, ”Hedvig”, ”Juan”, ”Lars”,
”Guido”, ”Patric”, ”Maria”, ”Ann”};
set<string, less<string> > nameSet(names,names+7);
set<string, less<string> >::iterator iter; // set iterator
iter=nameSet.lower_bound(”K”);
// set iterator to lower start value ”K”
while (iter != nameSet.upper_bound(”Q”))
cout << *iter++ << endl;
// displays Lars, Maria, Ole, Patric
47
48. Maps and Multimaps
A map stores pairs <key, value> of a key object and
associated value object.
The key object contains a key that will be searched
for and the value object contains additional data
The key could be a string, for example the name of
a person and the value could be a number, for
example the telephone number of a person
48
50. Algorithms
Implement simple, or not-so-simple loops on
ranges
copy, find, but also partition, sort, next-permutation
Specify their need in terms of iterator categories
They do not care about the exact class
Must pay attention to the iterators provided by
containers
Often exist in several versions
One uses default comparison, user-defined value
Other calls user-provided predicate, function
Some impose requirement on the data
binary_search needs sorted data
Tip: swap(c1,c2) would swap c1 and c2 irrespective of their
data type 50
51. Fill and Generate
• fill(iterator1, iterator2, value);
fills the values of the elements between iterator1 and iterator2
with value
• fill_n(iterator1, n, value);
changes specified number of elements starting at iterator1 to
value
• generate(iterator1, iterator2, function);
similar to fill except that it calls a function to return value
• generate_n(iterator1, n, function)
same as fill_n except that it calls a function to return value
51
52. Comparing sequences of values
• bool equal(iterator1, iterator2, iterator3);
- compares sequence from iterator1 to iterator2 with the sequence
beginning at iterator3
- return true is they are equal, false otherwise
• pair mismatch(iterator1, iterator2, iterator3);
- compares sequence from iterator1 to iterator2 with the sequence
starting at iterator3
- returns a pair object with iterators pointing to where mismatch
occurred
- example of the a pair object
pair <<vector>::iterator, <vector>::iterator> par_obj;
52
53. Removing elements from containers
• iterator remove(iterator1, iterator2, value);
- removes all instances of value in a range iterator1 to iterator2
- does not physically remove the elements from the sequence
- moves the elements that are not removed forward
- returns an iterator that points to the "new" end of container
• iterator remove_copy(iterator1, iterator2, iterator3,
value);
- copies elements of the range iterator1-iterator2 that are not equal to
value into the sequence starting at iterator3
- returns an iterator that points to the last element of the sequence
starting at iterator3
53
54. Replacing elements (1)
• replace( iterator1, iterator2, value, newvalue );
replaces value with newvalue for the elements located in the range
iterator1 to iterator2
• replace_if( iterator1, iterator2, function, newvalue );
replaces all elements in the range iterator1-iterator2 for
which function returns true with newvalue
54
55. Replacing elements (2)
• replace_copy( iterator1, iterator2, iterator3, value,
newvalue );
replaces and copies elements of the range iterator1-iterator2 to iterator3
• replace_copy_if( iterator1, iterator2, iterator3,
function, newvalue );
replaces and copies elements for which function returns true where
iterator3
55
56. Search algorithms
• iterator find(iterator1, iterator2, value)
returns an iterator that points to first occurrence
of value
• iterator find_if(iterator1, iterator2, function)
returns an iterator that points to the first element
for which function returns true.
56
57. Sorting algorithms
• sort(iterator1, iterator2)
sorts elements in ascending order
• binary_search(iterator1, iterator2, value)
searches in an ascending sorted list for value using a binary
search
57
58. Copy and Merge
• copy(iterator1, iterator2, iterator3)
copies the range of elements from iterator1 to iterator2 into
iterator3
• copy_backward(iterator1, iterator2, iterator3)
copies in reverse order the range of elements from iterator1 to
iterator2 into iterator3
• merge(iter1, iter2, iter3, iter4, iter5)
ranges iter1-iter2 and iter3-iter4 must be sorted in ascending
order and copies both lists into iter5 in ascending order
58
59. Unique and Reverse order
• iterator unique(iterator1, iterator2)
- removes (logically) duplicate elements from a sorted list
- returns iterator to the new end of sequence
• reverse(iterator1, iterator2)
- reverses elements in the range of iterator1 to iterator2
59
60. Utility algorithms (1)
• random_shuffle(iterator1, iterator2)
randomly mixes elements in the range iterator1-
iterator2
• int count(iterator1, iterator2, value)
returns number of instances of value in the range
• int count_if(iterator1, iterator2, function)
counts number of instances for which function
returns true
60
61. Utility algorithms (2)
• iterator min_element(iterator1, iterator2)
returns iterator to smallest element
• iterator max_element(iterator1, iterator2)
returns iterator to largest element
• accumulate(iterator1, iterator2)
returns the sum of the elements in the range
61
62. Utility algorithms (3)
• for_each(iterator1, iterator2, function)
calls function on every element in range
• transform(iterator1, iterator2, iterator3, function)
calls function for all elements in range iterator1-
iterator2, and copies result to iterator3
62
63. Algorithms on sets (1)
• includes(iter1, iter2, iter3, iter4)
returns true if iter1-iter2 contains iter3-iter4.
Both sequences must be sorted
• set_difference(iter1, iter2, iter3, iter4,iter5)
copies elements in range iter1-iter2 that do not
exist in second range iter3-iter4 into iter5
• set_intersection(iter1, iter2, iter3, iter4, iter5)
copies common elements from the two ranges
iter1-iter2 and iter3-iter4 into iter5
63
64. Algorithms on sets (2)
• set_symmetric_difference(iter1, iter2, iter3, iter4, iter5)
copies elements in range iter1-iter2 that are not in
range iter3-iter4 and vice versa, into iter5. Both sets must
be sorted
• set_union(iter1, iter2, iter3, iter4, iter5)
copies elements in both ranges to iter5. Both sets must
be sorted
64
65. For_Each() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
void show(int n)
{
printf(”%d ”,n);
}
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int> v(arr, arr+4); // initialize vector with C array
for_each (v.begin(), v.end(), show); // apply function show
// to each element of vector v65
66. Find() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
int key;
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
pritnf(”enter value :”);
scanf(”%d ”,key);
iter=find(v.begin(),v.end(),key); // finds integer key in v
if (iter != v.end()) // found the element
printf(”Element %d foundn”,key);
else
printf(”Element %d not in vector”, key);
66
67. Find_If() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
Bool mytest(int n) { return (n>21) && (n <36); };
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
iter=find_if(v.begin(),v.end(),mytest);
// finds element in v for which mytest is true
if (iter != v.end()) // found the element
printf(”Found %dn”,iter);
else
printf(”Not found”); 67
68. Count_If() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
Bool mytest(int n) { return (n>14) && (n <36); };
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C
array
vector<int> v(arr, arr+7); // initialize vector with C
array
int n=count_if(v.begin(),v.end(),mytest);
// counts element in v for which mytest is true
printf(”found %d elementsn”, n );
68
69. List Container
An STL list container is a double linked list, in which
each element contains a pointer to its successor and
predecessor.
It is possible to add and remove elements from both
ends of the list
Lists do not allow random access but are efficient to
insert new elements and to sort and merge lists
69
71. Insert Iterators
If you normally copy elements using the copy algorithm you
overwrite the existing contents
#include <list>
int arr1[]= { 1, 3, 5, 7, 9 };
int arr2[]= { 2, 4, 6, 8, 10 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
list<int> l2(arr2, arr2+5); // initialize l2 with arr2
copy(l1.begin(), l1.end(), l2.begin());
// copy contents of l1 to l2 overwriting the elements in l2
// l2 = { 1, 3, 5, 7, 9 }
71
72. Insert Iterators
With insert operators you can modify the behavior of the copy algorithm
back_inserter : inserts new elements at the end
front_inserter : inserts new elements at the beginning
inserter : inserts new elements at a specified location
#include <list>
int arr1[]= { 1, 3, 5, 7, 9 };
int arr2[]= { 2, 4, 6, 8, 10 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
list<int> l2(arr2, arr2+5); // initialize l2 with arr2
copy(l1.begin(), l1.end(), back_inserter(l2)); // use back_inserter
// adds contents of l1 to the end of l2 = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 }
copy(l1.begin(), l1.end(), front_inserter(l2)); // use front_inserter
// adds contents of l1 to the front of l2 = { 9, 7, 5, 3, 1, 2, 4, 6, 8, 10 }
copy(l1.begin(), l1.end, inserter(l2,l2.begin());
// adds contents of l1 at the ”old” beginning of l2 = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 }
72
73. Sort & Merge
Sort and merge allow you to sort and merge elements
in a container
#include <list>
int arr1[]= { 6, 4, 9, 1, 7 };
int arr2[]= { 4, 2, 1, 3, 8 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
list<int> l2(arr2, arr2+5); // initialize l2 with arr2
l1.sort(); // l1 = {1, 4, 6, 7, 9}
l2.sort(); // l2= {1, 2, 3, 4, 8 }
l1.merge(l2); // merges l2 into l1
// l1 = { 1, 1, 2, 3, 4, 4, 6, 7, 8, 9}, l2= {}
73
74. Functions Objects
Some algorithms like sort, merge, accumulate can take a
function object as argument.
A function object is an object of a template class that has a
single member function : the overloaded operator ()
It is also possible to use user-written functions in place of
pre-defined function objects
#include <list>
#include <functional>
int arr1[]= { 6, 4, 9, 1, 7 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
l1.sort(greater<int>()); // uses function object
greater<int>
// for sorting in reverse order l1 = { 9, 7, 6, 4, 1 }
74
75. Function Objects
The accumulate algorithm accumulates data over the elements
of the containing, for example computing the sum of elements
#include <list>
#include <functional>
#include <numeric>
int arr1[]= { 6, 4, 9, 1, 7 };
list<int> l1(arr1, arr1+5); // initialize l1 with arr1
int sum = accumulate(l1.begin(), l1.end() , 0, plus<int>());
int sum = accumulate(l1.begin(), l1.end(),0); // equivalent
int n = accumulate(l1.begin(), l1.end() , 100, minus<int>());
75
76. User Defined Function Objects
class squared _sum // user-defined function object
{
public:
int operator()(int n1, int n2) { return n1+n2*n2; }
};
int sq = accumulate(l1.begin(), l1.end() , 0,
squared_sum() );
// computes the sum of squares
76
77. User Defined Function Objects
template <class T>
class squared _sum // user-defined function object
{
public:
T operator()(T n1, T n2) { return n1+n2*n2; }
};
vector<complex> vc;
complex sum_vc;
vc.push_back(complex(2,3));
vc.push_back(complex(1,5));
vc.push_back(complex(-2,4));
sum_vc = accumulate(vc.begin(), vc.end() ,
complex(0,0) , squared_sum<complex>() );
// computes the sum of squares of a vector of complex numbers
77