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

Lecture21

The document provides an overview of the Standard Template Library (STL) in C++, which consists of containers, iterators, and algorithms. It details various types of containers, including sequence and associative containers, as well as the different categories of iterators that facilitate access to elements within these containers. Additionally, it highlights the functionalities and limitations of each iterator type, along with examples and best practices for their use.

Uploaded by

nazhasan52
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture21

The document provides an overview of the Standard Template Library (STL) in C++, which consists of containers, iterators, and algorithms. It details various types of containers, including sequence and associative containers, as well as the different categories of iterators that facilitate access to elements within these containers. Additionally, it highlights the functionalities and limitations of each iterator type, along with examples and best practices for their use.

Uploaded by

nazhasan52
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Section 2.12.

Containers, Iterators, and Algorithms

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 776


Standard Template Library (STL)

■ large part of C++ standard library is collection of class/function templates


known as standard template library (STL)
■ STL comprised of three basic building blocks:
1 containers
2 iterators
3 algorithms
■ containers store elements for processing (e.g., vector)
■ iterators allow access to elements for processing (which are often, but not
necessarily, in containers)
■ algorithms perform actual processing (e.g., search, sort)

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 777


Containers

■ container: class that represents collection/sequence of elements


■ usually container classes are template classes
■ sequence container: collection in which every element has certain
position that depends on time and place of insertion
■ examples of sequence containers include:
2 array (fixed-size array)
2 vector (dynamic-size array)
2 list (doubly-linked list)

■ ordered/unordered associative container: collection in which position of


element in depends on its value or associated key and some predefined
sorting/hashing criterion
■ examples of associative containers include:
2 set (collection of unique keys, sorted by key)
2 map (collection of key-value pairs, sorted by key, keys are unique)

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 778


Sequence Containers and Container Adapters

Sequence Containers
Name Description
array fixed-size array
vector dynamic-size array
deque double-ended queue
forward_list singly-linked list
list doubly-linked list

Container Adapters
Name Description
stack stack
queue FIFO queue
priority_queue priority queue

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 779


Associative Containers

Ordered Associative Containers


Name Description
set collection of unique keys, sorted by key
map collection of key-value pairs, sorted by key, keys are unique
multiset collection of keys, sorted by key, duplicate keys allowed
multimap collection of key-value pairs, sorted by key, duplicate keys al-
lowed

Unordered Associative Containers


Name Description
unordered_set collection of unique keys, hashed by key
unordered_map collection of key-value pairs, hashed by key, keys are
unique
unordered_multiset collection of keys, hashed by key, duplicate keys al-
lowed)
unordered_multimap collection of key-value pairs, hashed by key, duplicate
keys allowed

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 780


Typical Sequence Container Member Functions

■ some member functions typically provided by sequence container classes


listed below (where T denotes name of container class)
Function Description
T() create empty container (default constructor)
T(const T&) copy container (copy constructor)
T(T&&) move container (move constructor)
~T destroy container (including its elements)
empty test if container empty
size get number of elements in container
push_back insert element at end of container
clear remove all elements from container
operator= assign all elements of one container to other
operator[] access element in container

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 781


Container Example

1 #include <iostream>
2 #include <vector>
3
4 int main() {
5 std::vector<int> values;
6
7 // append elements with values 0 to 9
8 for (int i = 0; i < 10; ++i) {
9 values.push_back(i);
10 }
11
12 // print each element followed by space
13 for (int i = 0; i < values.size(); ++i) {
14 std::cout << values[i] << ’ ’;
15 }
16 std::cout << ’\n’;
17 }
18
19 /* This program produces the following output:
20 0 1 2 3 4 5 6 7 8 9
21 */

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 782


Motivation for Iterators

■ different containers organize elements (of container) differently in memory


■ want uniform manner in which to access elements in any arbitrary
container
■ organization of elements in array/vector container:

v[0] v[1] v[2] v[3]

begin end
■ organization of elements in doubly-linked list container:

v[0] v[1] v[2] v[3]

begin end

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 783


Motivation for Iterators (Continued)

■ consider array/vector container with int elements:

v[0] v[1] v[2] v[3]

begin end
■ suppose we want to set all elements in container to zero
■ we could use code like:
// int* begin; int* end;
for (int* iter = begin; iter != end; ++iter)
*iter = 0;

■ could we make similar-looking code work for more complicated


organization like doubly-linked list?
■ yes, create user-defined type that provides all pointer operations used
above (e.g., dereference, increment, comparison, assignment)
■ this leads to notion of iterator

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 784


Iterators
■ iterator: object that allows iteration over collection of elements, where
elements are often (but not necessarily) in container
■ iterators support many of same operations as pointers
■ in some cases, iterator may actually be pointer; more frequently, iterator is
user-defined type
■ five different categories of iterators: 1) input, 2) output, 3) forward,
4) bidirectional, and 5) random access
■ iterator has particular level of functionality, depending on category
■ one of three possibilities of access order:
1 forward (i.e., one direction only)
2 forward and backward
3 any order (i.e., random access)
■ one of three possibilities in terms of read/write access:
1 can only read referenced element (once or multiple times)
2 can only write referenced element (once or multiple times)
3 can read and write referenced element (once or multiple times)
■ const and mutable (i.e., non-const) variants (i.e., read-only or read/write
access, respectively)
Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 785
Abilities of Iterator Categories

Category Ability Providers


Input Reads (once only) istream
forward (istream_iterator)
Output Writes (once only) ostream
forward (ostream_iterator),
inserter_iterator
Forward Reads and writes forward_list,
forward unordered_set,
unordered_multiset,
unordered_map,
unordered_multimap
Bidirectional Reads and writes list, set, multiset,
forward and backward map, multimap
Random access Reads and writes deque
with random access
Contiguous Random access and (built-in) array, array,
contiguous in memory vector, string

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 786


Input Iterators

Expression Effect
T(a) copies iterator (copy constructor)
*a dereference as rvalue (i.e., read only); cannot
a->m dereference at old position
++a steps forward (returns new position)
a++ steps forward
a == b test for equality
a != b test for inequality
■ not assignable (i.e., no assignment operator)

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 787


Output Iterators

Expression Effect
T(a) copies iterator (copy constructor)
*a dereference as lvalue (i.e., write only); can only
a->m be dereferenced once; cannot dereference at old
position
++a steps forward (returns new position)
a++ steps forward (returns old position)
■ not assignable (i.e., no assignment operator)
■ no comparison operators (i.e., operator==, operator!=)

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 788


Forward Iterators

Expression Effect
T() default constructor
T(a) copy constructor
a = b assignment
*a dereference
a->m
++a steps forward (returns new position)
a++ steps forward (returns old position)
a == b test for equality
a != b test for inequality
■ must ensure that valid to dereference iterator before doing so

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 789


Bidirectional Iterators

■ bidirectional iterators are forward iterators that provide additional


functionality of being able to iterate backward over elements
■ bidirectional iterators have all functionality of forward iterators as well as
those listed in table below
Expression Effect
--a steps backward (returns new position)
a-- steps backward (returns old position)

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 790


Random-Access Iterators
■ random access iterators provide all functionality of bidirectional iterators
as well as providing random access to elements
■ random access iterators provide all functionality of bidirectional iterators
as well as those listed in table below
Expression Effect
a[n] dereference element at index n (where n can be nega-
tive)
a += n steps n elements forward (where n can be negative)
a -= n steps n elements backward (where n can be negative)
a + n iterator for nth next element
n + a iterator for nth next element
a - n iterator for nth previous element
a - b distance from a to b
a < b test if a before b
a > b test if a after b
a <= b test if a not after b
a >= b test if a not before b
■ pointers (built into language) are examples of random-access iterators

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 791


Contiguous Iterators

■ contiguous iterators provide all functionality of random-access iterators


and guarantee that elements stored contiguously in memory
■ pointer to element in (built-in) array is example of contiguous iterator

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 792


Iterator Category Hierarchy

Input Iterator Output Iterator

Forward Iterator

Bidirectional Iterator

Random-Access Iterator

Contiguous Iterator

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 793


Iterator Example

1 #include <iostream>
2 #include <vector>
3
4 int main() {
5 std::vector<int> values(10);
6
7 std::cout << "number of elements: " <<
8 (values.end() - values.begin()) << ’\n’;
9
10 // initialize elements of vector to 0, 1, 2, ...
11 for (std::vector<int>::iterator i = values.begin();
12 i != values.end(); ++i) {
13 *i = i - values.begin();
14 }
15
16 // print elements of vector
17 for (std::vector<int>::const_iterator i =
18 values.cbegin(); i != values.cend(); ++i) {
19 std::cout << ’ ’ << *i;
20 }
21 std::cout << ’\n’;
22 }

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 794


Iterator Gotchas

■ do not dereference iterator unless it is known to validly reference some


object
■ some operations on container can invalidate some or all iterators
referencing elements in container
■ critically important to know which operations invalidate iterators in order
to avoid using iterator that has been invalidated
■ incrementing iterator past end of container or decrementing iterator before
beginning of container results in undefined behavior
■ input and output iterators can only be dereferenced once at each position

Copyright © 2015–2021 Michael D. Adams Programming in C++ Version 2021-04-01 795

You might also like