Standard Template Library
(STL)
Learning Objectives
To understand the components of
Standard Template Library (STL).
To understand how and when to use
STLs vector, set, multiset, map, and
multimap.
To understand how to use iterator.
To understand how to use STL find and
sort algorithms.
Standard Template Library (STL)
STL provides powerful, template-based, reusable
components that implement many common data
structures and algorithms used to process those data
structures.
The STL was conceived and designed for
performance and flexibility.
What is STL?
The Standard Template Library provides a set of well
structured generic C++ components that work together in a
seamless way.
A collection of composable class & function templates
Helper class & function templates: operators, pair
Container & iterator class templates
Generic algorithms that operate over iterators
Function objects
Adaptors
Enables generic programming in C++
Each generic algorithm can operate over any iterator
for
which the necessary operations are provided
Extensible: can support new algorithms, containers,
iterators
Generic Programming: Why Use
STL?
Reuse: write less, do more
STL hides complex, tedious & error prone details
The programmer can then focus on the problem at
hand
Type-safe plug compatibility between STL
components
Flexibility
Iterators decouple algorithms from containers
Unanticipated combinations easily supported
Efficiency
Templates avoid virtual function overhead
Strict attention to time complexity of algorithms
STL Components
STL has 3 components (CIA): Containers, Algorithms,
Iterators.
Containers: Containers are data structures or a
collection of objects. Example: vector, list, set,
map, etc.
Iterators: Iterators are similar to pointers and are used
to point to container elements.
Algorithms: Algorithm are functions for processing
container elements. Example: copy, sort, find, etc.
STL Containers
STL has many containers, divided into 3 groups:
sequential, associative, adaptor.
Sequential containers represent linear data structures,
e.g. vectors, list, deque.
Associative containers are nonlinear containers that
typically can locate (search) elements stored in the
containers quickly, e.g. set, multiset, map,
multimap.
Container adapters are simply variations of the above
containers, e.g. stack, queue, priority_queue. The
container adapters do not support iterators.
Useful Sequential Containers
Container
Description
list
Bidirectional/Doubly linked list.
Best for rapid insertion and deletion anywhere.
vector
"Array" that grows automatically,
Best for rapid insertion and deletion at back.
Support direct access to any elementvia operator "[]".
deque
"Array" that grows automatically.
Best for rapid insertion and deletion at front and back.
Useful Associative Containers
Container
Description
set
No duplicate element allowed.
Elements are automatically sorted.
Best for rapid lookup (searching) of element.
multiset
set that allows duplicate elements.
map
Collection of (key, value) pairs with non-duplicate key.
Elements are automatically sorted by key.
Best for rapid lookup of key.
multimap
map that allows duplicate keys.
Useful Container Adaptors
Container
Description
stack
Last-in, first-out (LIFO) data structure.
queue
First-in, first-out (FIFO) data structure.
priority_queue
Highest priority element is always the first element
out.
10
STL Iterator
Iterators are similar to pointers and are used to point to
container elements.
The dereferencing operator (*) dereferences an iterator
so that you can use the element to which it points.
The ++ operation on an iterator moves it to the
containers next element.
Container's begin method returns an iterator pointing to
the first element of the container.
Container's end method returns an iterator pointing to
the first element past the end of the container (an
element that doesnt exist).
11
Iterator Example
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.push_back(4);
v.push_back(2);
v.push_back(7);
v.push_back(6);
for (int i = 0; i < [Link](); i++)
cout << v[i] << " ";
cout << endl;
// Same result as 'for' loop.
for (vector<int>::iterator it = [Link]();
it != [Link]();
it++)
cout << *it << " ";
cout << endl;
Output:
4 2 7 6
4 2 7 6
Iterator type must
match container type.
Initialize iterator it to
the first element of
container.
Move to the next
element.
Use iterator it like a
pointer.
12
STL Algorithms
Many STL algorithms accept iterator as function
argument. See next slide for sort function.
Many STL algorithms returns an iterator. See the
example on STL set class for find function.
13
STL Algorithm sort
#include <iostream>
#include <algorithm> // sort()
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.push_back(4);
v.push_back(2);
v.push_back(7);
v.push_back(6);
cout << "Vector elements unsorted:\n";
for (int i = 0; i < [Link](); i++)
cout << v[i] << " ";
sort ([Link](), [Link]());
cout << "\nVector elements sorted:\n";
for (int i = 0; i < [Link](); i++)
cout << v[i] << " ";
}
vector elements can
be sorted using STL
algorithm sort
function
Vector elements unsorted:
4 2 7 6
Vector elements sorted:
2 4 6 7
14
STL set Class
A set is a collection of non-duplicate sorted elements called keys.
set <key_type> s;
key_type is the data types of the key/element.
Use set when you want a sorted collection and you do not need
random access to its elements.
Use insert() method to insert an element into a set:
set <int> s;
[Link] (321);
Duplicates are ignored when inserted.
iterator is required to iterate/visit the elements in set. Operator[] is
not supported.
Use find() method to look up a specified key in a set .
15
STL set Class
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s;
[Link] (321);
[Link] (-999);
[Link] (18);
[Link] (-999); // duplicate is ignored
set<int>::iterator it = [Link]();
while (it != [Link]())
cout << *it++ << endl; // -999 18 321
int target;
cout << "Enter an integer: ";
cin >> target;
it = [Link] (target);
if (it == [Link]()) // not found
cout << target << " is NOT in set.";
else
cout << target << " is IN set.";
}
Output1:
-999
18
321
Enter an integer:
5
5 is not in set.
Use iterator to
iterate the set.
Output2:
-999
18
321
Enter an integer:
321
321 is IN set.
16
STL multiset Class
#include <iostream>
#include <set>
using namespace std;
int main() {
multiset<int> s;
[Link] (321);
[Link] (-999);
[Link] (18);
[Link] (-999); // duplicate
set<int>::iterator it = [Link]();
while (it != [Link]())
cout << *it++ << endl;
}
Output:
-999
-999
18
321
multiset allows
duplicate keys
17
STL map Class
A map is a collection of (key,value) pairs sorted by the keys.
map <key_type, value_type> m;
key_type and value_type are the data types of the key and
the value respectively.
In array the index is always int starting from 0, whereas in
map the key can be of other data type.
map cannot contain duplicate key (multimap can).
map <char, string> m;
m['A'] = "Apple";
m['A'] = "Angel"; // key 'A' already in the
// map, new 'A' is ignored.
// m['A'] is still "Apple".
18
STL map Class
#include <iostream>
#include <string>
#include <map> // map, multimap
using namespace std;
int main() {
map <char, string> m;
m['C'] = "Cat";
// insert
m['A'] = "Apple";
m['B'] = "Boy";
cout << m['A'] << " " // retrieve
<< m['B'] << " "
<< m['C'] << endl;
map <char, string>::iterator it;
it = [Link]();
while (it != [Link]()) {
cout << it->first << " "
<< it->second << endl;
it++;
}
char key;
cout << "Enter a char: ";
cin >> key;
it = [Link] (key);
if (it == [Link]())
cout << key
<< " is NOT in map.";
else
cout << key << " is IN map.";
}
first refers to the key of
current element whereas
second refers to the value
of of current element
19
STL map Class
#include <iostream>
#include <string>
#include <map> // map, multimap
using namespace std;
int main() {
map <char, string> m;
m['C'] = "Cat";
// insert
m['A'] = "Apple";
m['B'] = "Boy";
cout << m['A'] << " " // retrieve
<< m['B'] << " "
<< m['C'] << endl;
map <char, string>::iterator it;
it = [Link]();
while (it != [Link]()) {
cout << it->first << " "
<< it->second << endl;
it++;
}
char key;
cout << "Enter a char: ";
cin >> key;
it = [Link] (key);
if (it == [Link]())
cout << key
<< " is NOT in map.";
else
cout << key << " is IN map.";
}
Output 1:
Apple Boy Cat
A Apple
B Boy
C Cat
Enter a char: Z
Z is NOT in map
Output 2:
Apple Boy Cat
A Apple
B Boy
C Cat
Enter a char: C
C is IN map
20
STL multimap Class
A multimap is similar to map but it allows duplicate keys.
However, insert method and a pair object must be used
when inserting a (key,value) pair into multimap.
The pair object and the multimap must have the same key
type and value type.
Operator [ ] is not supported. Iterator must be used to locate a
element.
multimap <char,string> mm;
[Link] (pair<char,string>('A',"Apple"));
[Link] (pair<char,string>('A',"Angel"));
// mm has 2 elements with 'A' as key.
21
STL multimap Class
#include <iostream>
#include <string>
#include <map> // map, multimap
using namespace std;
int main() {
multimap <char,string> mm;
[Link] (
pair<char,string>('C',"Cat"));
[Link] (
pair<char,string>('A',"Apple"));
[Link] (
pair<char,string>('B',"Boy"));
[Link] (
pair<char,string>('A',"Angle"));
map <char, string>::iterator it;
it = [Link]();
while (it != [Link]()) {
cout << it->first << " "
<< it->second << endl;
it++;
}
char key;
cout << "Enter a char: ";
cin >> key;
it = [Link] (key);
if (it == [Link]())
cout << key
<< " is NOT in map.";
else
cout << key << " is IN map.";
}
Output 1:
A Apple
A Angle
B Boy
C Cat
Enter a char: Z
Z is NOT in map
Output 2:
A Apple
A Angle
B Boy
C Cat
Enter a char: C
C is IN map
22
STL less and greater Function Objects
By default, STL sort function, set, map, and other
classes use the STL less function object to sort the
elements from the smallest element first to the largest.
To sort by the largest element first, pass the STL
greater function object to the STL container
constructor.
set <int> s1;
// Smallest to largest.
set <int, less<int> > s2;
// Same sorting as s1.
set <int, greater<int> > s3; // Largest to smallest.
23
STL greater Function Object
#include <iostream>
#include <set>
using namespace std;
int main() {
multiset<int, greater<int> > s;
[Link] (321);
[Link] (-999);
[Link] (18);
[Link] (-999); // duplicate
set<int>::iterator it = [Link]();
while (it != [Link]())
cout << *it++ << endl;
}
Output:
321
18
-999
-999
Largest first
24