PPT13 Standard Template Library
PPT13 Standard Template Library
11/20/2024
Components of the STL
• Containers – Classes that store collections of elements. Eg. Vector
These components work together, with containers holding the data, iterators providing
a way to access the data, and algorithms performing operations on the data.
Access Functions:
Function Description
at(index) Accesses the element at the specified position (bounds-checked).
front() Accesses the first element.
back() Accesses the last element.
© Dr. Lokendra Vishwakarma
11/20/2024 data() Returns a pointer to the underlying array.
[email protected]
Sequence Containers: vector (Example)
Access Functions:
Function Description
at(index) Accesses the element at the specified position (bounds-checked).
front() Accesses the first element.
back() Accesses the last element.
11/20/2024 data() Returns a pointer
© Dr. Lokendra to the underlying array.
Vishwakarma
[email protected]
Sequence Containers: deque (Example)
Access Functions:
Function Description
front() Accesses the first element.
back() Accesses the last element.
© Dr. Lokendra Vishwakarma
11/20/2024
[email protected]
Sequence Containers: list
Modifier Functions:
Function Description
push_back(value), push_front(value) Adds elements to the end or beginning.
Pop_back(value), pop_front(value) Removes elements from the end or beginning.
insert(position, value) Inserts an element at a given position.
erase(position) Removes an element from a specified position.
clear() Removes all elements.
remove(value) Removes all elements equal to a value.
sort() Sorts the list.
reverse() Reverse the list
In C++, an iterator is an object that points to an element within a container. Think of an iterator
as a pointer that “points” to the location of an element but doesn’t directly hold the element's
value. Therefore, to access the actual value stored at the iterator’s position, you need to
dereference the iterator.
Types of Iterators
• Input Iterator: Can read data sequentially.
• Output Iterator: Can write data sequentially.
• Forward Iterator: Can read or write in a single direction.
• Bidirectional Iterator: Can move both forward and backward.
• Random Access Iterator: Can jump to any element in constant time.
© Dr. Lokendra Vishwakarma
11/20/2024
[email protected]
Using Iterators to Traverse Containers
Algorithm Description
std::sort Sorts elements in a range in ascending order.
std::find Finds the first occurrence of a value in a range.
std::count Counts occurrences of a specific value in a range.
std::reverse Reverses the order of elements in a range.
std::accumulate Computes the sum of elements in a range.
© Dr. Lokendra Vishwakarma
11/20/2024
[email protected]
Example of Using Algorithms