Beruflich Dokumente
Kultur Dokumente
STL extensively uses generic programming based on templates Divided into three components:
- Containers: data structures that store objects of any type - Iterators: used to manipulate container elements - Algorithms: searching, sorting and many others
Containers
Two types of containers
- Sequence containers: - linear data structures such as vectors and linked lists - Associative containers: - non-linear containers such as hash tables
Iterators
Iterators are pointers to elements of first-class containers
Type const_iterator defines an iterator to a container element that cannot be modified Type iterator defines an iterator to a container element that can be modified
All first-class containers provide the members functions begin() and end()
return iterators pointing to the first and last element of the container
Iterators (cont.)
If the iterator it points to a particular element, then
- it++ (or ++it) points to the next element and - *it refers to the value of the element pointed to by it
The iterator resulting from end() can only be used to detect whether the iterator has reached the end of the container
Sequence Containers
All objects of the same type Store objects in strictly linear order Data organized as an array or linked list Container vector, deque and list is varying-length sequence of elements of type T.
Sequence Containers
STL provides three sequence containers
- vector: based on arrays - deque (double-ended queue): based on arrays - list: based on linked lists
To use vectors, we need to include the header <vector> Some functions of the class vector include
- size, capacity, insert
for (it = v.begin(); it != v.end(); it++) { cout << *it << \n; } return 0;
Vector
deque (cont.)
Additional storage for a deque is allocated using blocks of memory
- that are maintained as an array of pointers to those blocks
Deque Example.
#include < deque.h > int main () { deque< int > d; d.push_back (4); // Add after end. d.push_back (9); d.push_back (16); d.push_front (1); // Insert at beginning. for (int i = 0; i < d.size (); i++) cout << "d[" << i << "] = " << d[i] << endl; cout << endl; d.pop_front (); // Erase first element. d[2] = 25; // Replace last element. for (i = 0; i < d.size (); i++) cout << "d[" << i << "] = " << d[i] << endl; return 0; }
output:
Associative Containers
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
- set does not 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
The ordering of the keys is determined by the STL comparator function object less<T>
typedef multimap< int, double, less< int > > mp_type; // creates a mutlimap type
int main() { mp_type mp;
Thank you..