L8c
L8c
CodeClass[5]
4
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
Strings
6
Hello World - C
#include <stdio.h>
void main()
{
// create string ‘str’ = “Hello world!”
char *str = “Hello World!”;
//OR
char str1[] = “Hello World!”;
printf(“%s\n”, str);
}
7
Hello World – C++
#include <iostream> //for cout
#include <cstdio> //for printf
#include <string>
int main()
{
// create string ‘str’ = “Hello world!”
string str = “Hello World!”;
9
Creating strings
10
string length
#include <string>
11
The size method
str.size() ???
In C we had structs containing only data, In
C++, we have :
class string
{
…
public:
…
unsigned int size();
…
};
12
String concatenation
13
String comparison
if ( str1 == str2 )
/* do something */
else
/* do something else */
14
String assignment
To assign one string to another
use the “=“ operator.
15
Containers, Iterators, Algorithms
Objects Iterator
Algorithm
Iterator Iterator
Algorithm
16
Containers
17
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
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
20
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
Defining a new vector
Header file: <vector>
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
Operations on vector
iterator begin();
iterator end();
bool empty();
void push_back(const T& x);
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
void clear();
….
23
Vector Container
int array[5] = {12, 7, 9, 21, 13 };
vector<int> v(array,array+5);
12 7 9 21 13
v.pop_back(); v.push_back(15);
12 7 9 21 12 7 9 21 15
0 1 2 3 4
12 7 9 21 15
v.begin(); v[3] 24
Vector Container
25
Vector Container
#include <vector>
#include <cstdio>
26
Tip : vector<bool>
27
Tip : reserve()
29
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.
vector<int>
array_ 17
vector<int>::iterator
4
23 The iterator corresponding to
12 the class vector<int> is of
the type vector<int>::iterator
size_ 4
30
Iterators
The member functions begin() and end() return an
iterator to the first and past the last element of a
container
vector<int> v
v.begin()
array_ 17
4
23
12 v.end()
size_ 4
31
Iterators
vector<int> v
i1
array_ 17
4
i2
23
12
i3
size_ 4
32
Common Iterator Operations
33
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
for(i=0;i<n;i++)
printf(”%d ”,v[i]);
36
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
• Example:
- A queue of int using a list: queue <int, list<int>> q1;
- A queue of int using a deque: queue <int> q2;
39
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
Priority Queue Container
• Priority Queues are implemented with vector (by
default) or deque
41
Associative Containers
42
Associative Containers
• Associative containers use keys to store and retrieve
elements
43
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
Set A Set B
Buick Ford
5 1 3
Jeep BMW
6 27 15
44
Associative Containers: multiset
• Multisets are implemented using a red-black binary
search tree for fast storage and retrieval of keys
45
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
Set and Multisets
iter=nameSet.lower_bound(”K”);
// set iterator to lower start value ”K”
while (iter != nameSet.upper_bound(”Q”))
cout << *iter++ << endl;
47
Maps and Multimaps
48
Maps and Multimaps
#include <map>
string names[]= {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”, ”Patric”,
”Maria”, ”Ann”};
int numbers[]= {75643, 83268, 97353, 87353, 19988, 76455,
77443,12221};
map<string, int, less<string> > phonebook;
map<string, int, less<string> >::iterator iter;
for (int j=0; j<8; j++)
phonebook[names[j]]=numbers[j]; // initialize map phonebook
for (iter = phonebook.begin(); iter !=phonebook.end(); iter++)
cout << (*iter).first << ” : ” << (*iter).second << endl;
cout << ”Lars phone number is ” << phonebook[”Lars”] << endl;
49
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
• fill_n(iterator1, n, value);
changes specified number of elements starting at iterator1 to
value
• generate_n(iterator1, n, function)
same as fill_n except that it calls a function to return value
51
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
52
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
53
Replacing elements (1)
• replace( iterator1, iterator2, value, newvalue );
replaces value with newvalue for the elements located in the range
iterator1 to iterator2
54
Replacing elements (2)
• replace_copy( iterator1, iterator2, iterator3, value,
newvalue );
replaces and copies elements of the range iterator1-iterator2 to iterator3
55
Search algorithms
• iterator find(iterator1, iterator2, value)
56
Sorting algorithms
• sort(iterator1, iterator2)
sorts elements in ascending order
57
Copy and Merge
• copy(iterator1, iterator2, iterator3)
copies the range of elements from iterator1 to iterator2 into
iterator3
58
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
Utility algorithms (1)
• random_shuffle(iterator1, iterator2)
randomly mixes elements in the range iterator1-
iterator2
60
Utility algorithms (2)
• iterator min_element(iterator1, iterator2)
returns iterator to smallest element
• accumulate(iterator1, iterator2)
returns the sum of the elements in the range
61
Utility algorithms (3)
• for_each(iterator1, iterator2, function)
calls function on every element in range
62
Algorithms on sets (1)
• includes(iter1, iter2, iter3, iter4)
returns true if iter1-iter2 contains iter3-iter4.
Both sequences must be sorted
63
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
64
For_Each() Algorithm
#include <vector>
#include <algorithm>
#include <cstdio>
void show(int n)
{
printf(”%d ”,n);
}
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 found\n”,key);
else
printf(”Element %d not in vector”, key);
66
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 %d\n”,iter);
else
printf(”Not found”); 67
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 elements\n”, n );
68
List Container
69
List Container
int array[5] = {12, 7, 9, 21, 13 };
list<int> li(array,array+5); 12 7 9 21 13
li.pop_back(); li.push_back(15);
12 7 9 21 12 7 9 21 15
li.pop_front(); li.push_front(8);
7 9 21 8 12 7 9 21 15
li.insert()
7 12 17 21 23
70
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
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
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
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
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
User Defined Function Objects
76
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