Download presentation
Presentation is loading. Please wait.
Published byIris Fletcher Modified over 9 years ago
1
The Standard Template Library Container Classes Version 1.0
2
The Standard Template Library provides a set of template classes designed to help you organize data in various useful ways. These are called containers or sometimes they are called collection classes.
3
There are two general kinds of containers: Sequential Containers Associative Containers
4
Sequence Containers Sequence containers are ordered collections Every element has a certain position Position depends on time and place of insertion There are three predefined sequence containers: Vector Deque List
5
Associative Containers Associative containers are sorted collections The position of an element depends upon its value Position is independent of the order of insertion There are four predefined associative containers: Set Multi-set Map Multi-map
6
Common Container Abilities All containers provide value rather than reference semantics. That is, containers copy elements internally when they are inserted, rather than managing references to them. Thus, each element in a container must have a public copy constructor.
7
Common Container Abilities All containers have an order. Each container provides functions that return an iterator that can be used to move through the elements in the container in order.
8
Common Container Abilities In general, operations on containers are not safe. It is the programmer’s responsibility to make sure that all parameters of an operation are valid and meet the requirements of the operation. Violating these requirements will result in an undefined behavior. Usually the STL does not throw exceptions!
9
Common Operations All container classes provide the following: OperationEffect CType c creates an empty container CType c1(c2) creates a container c1, copying c2 into it (c1 and c2 are the same type of container)
10
Initialization Every container class comes with a default constructor, a copy constructor, and a destructor. Constructors are provided to initialize a container with the elements of another container or from an array.
11
vector v; create an empty vector list l;... vector v(l.begin( ), l.end( )); create a vector and initialize it from a list int array[ ] = { 2, 17, 23, 46, 22};... vector v(array, array+sizeof(array)/sizeof(array[0]) ); create a vector and initialize from an array
12
Common Operations All container classes provide the following: OperationEffect CType c creates an empty container CType c1(c2) creates a container c1, copying c2 into it c.size( )returns the number of elements in c c.empty( )returns true if the container c is empty c.max_size( )returns the maximum number of elements ever possible c1 == c2returns true if the containers of the same type are equal c1 != c2returns true if the containers are not equal
13
Comparison operations are defined based on the following three rules: 1. Both containers are of the same type 2. Two containers are equal if their elements are equal and have the same order. 3. Lexicographical comparison is done to see if one container is less (or greater) than another.
14
Common Operations All container classes provide the following: OperationEffect c1.swap(c2) swaps the data in c1 and c2 (c1 and c2 are of the same type) c.begin( ) returns an iterator for the first element in c c.end( ) returns a sentinel marking the last element in c c.rbegin( ) returns a reverse iterator for the last element in c c.rend( ) returns a sentinel marking the first element in c c.clear( ) erases all elements from c - makes the container empty c.~CType ( ) destroys all elements and frees the memory
15
Efficiency of operations Operation vector list deque Constructor( ) O(1) O(1) O(1) Constructor(size) O(1) O(n) + O(1) Constructor(size, value) O(n) O(n) O(n) at(int) O(1) --- O(1) push_back(value) O(1) + O(1) O(1) + begin( ) / end( ) O(1) O(1) O(1) operator[ ] O(1) --- O(1) O(1) – independent of the number of elements O(n) – linear, depends on the value of n
16
Vectors Vectors store their elements in an internal dynamic array. You can access any element of a vector in constant time provided you know where the element is. Vectors provide good performance when adding or deleting elements at the end, but inserting or deleting in the middle is very expensive. This is because every element behind has to be moved to a new position. Insertion time is not constant! Vectors grow as required, but “growing” a vector is expensive, and invalidates all references, pointers and iterators for elements of the vector
17
Assignments Assignment (e.g. c1 = c2) is very expensive for any container class. Every element of the left container is destroyed and a copy made of every element of the right container. The default constructor, copy constructor, and overloaded assignment operators are used for each element in the copied container.
18
If you don’t need to re-use the source container, then the swap( ) function is much more efficient than doing an assignment, as it only swaps pointers. It does not make a copy.
19
Element Access OperationEffect c.at(idx)returns the element at index idx. Throws an exception if idx is out of range c[idx]returns the element at idx, no range checking c.front( )returns the first element (no check to see if one exists) c.back( )returns the last element (no check to see if one exists)
20
Inserting and Deleting Elements There are a number of operations defined to insert and delete elements from a Vector.
21
Inserting and Deleting Elements Operation Effect c.insert(pos,elem) inserts a copy of elem at pos and returns the position of the new element (pos is an iterator). c.push_back(elem) adds a copy of elem at the end of the vector c.pop_back( ) removes the last element in the vector c.erase(pos) removes the element at position pos and returns the position of the next element. c.resize(num) changes the size of the vector to num. Calls the default constructor for new elements. iterators must refer to valid positions. Do not try to remove an element from an empty container.
22
4 7 19 -5 vector v vector ::iterator p vector ::iterator vp = v.insert(p, 27);
23
4 7 19 -5 vector v vp vector ::iterator vp = v.insert(p, 27); 27
24
#include using namespace std; int main ( ) { vector sentence; sentence.reserve(10); sentence.push_back("Hello,"); sentence.push_back("how"); sentence.push_back("are"); sentence.push_back("you?"); vector ::iterator p; for (p = sentence.begin( ); p != sentence.end( ); p++) cout << *p << " "; cout << endl; system("PAUSE"); return 0; }
25
Deques Pronounced “deck”, a Deque is similar to a vector. It manages its elements with a dynamic array It provides random access A deque allows insertions and deletions at both ends, Which is fast. Insertion into the middle is slow. Element access and iterator movement is a bit slower than with a vector. Deques do not support the functions capacity( ) and reserve( )
26
Grows like a vector – but in both directions
27
Choose a deque if … You need to insert or delete from either end of the container You do not need to randomly access data in the container
28
Inserting and Deleting Elements Operation Effect c.insert(pos,elem) inserts a copy of elem at pos and returns the position of the new element. c.push_back(elem) adds a copy of elem at the end of the deque c.pop_back( ) removes the last element in the deque c.push_front(elem) adds a copy of elem at the front of the deque c.pop_front( ) removes the first element in the deque iterators must refer to valid positions. Do not try to remove an element from an empty container. new
29
The assign function void container::assign(size_type num, const T& value); The assign function replaces all existing elements of the container with num occurences of value.
30
#include using namespace std; int main ( ) { deque sentence; sentence.assign(3, string("middle stuff") ); sentence.push_back("end string"); sentence.push_front("front_string"); deque ::iterator p; for (p = sentence.begin( ); p != sentence.end( ); p++) cout << *p << "\n "; cout << endl; system("PAUSE"); return 0; }
31
Lists Lists are very different from vectors and deques A list does not provide random access. accessing an arbitrary element is slow. Inserting and deleting elements is fast at any position, not just the first and last. Inserting and deleting elements does not invalidate pointers, references, or iterators. Lists have the best exception safety of all of the STL containers. Either an operation works or it is a no-op in almost all cases.
32
Element Access Because a list does not support random access, only the following functions are provided for direct access: c.front( ) c.back( ) All other access must be done through iterators. Only bi-directional iterators are supported. Thus, you cannot call algorithms that require random access iterators. Sorting algorithms fall in this category.
33
Inserting and Deleting Elements Operation Effect c.insert(pos,elem) inserts a copy of elem at pos and returns the position of the new element. c.push_back(elem) adds a copy of elem at the end of the deque c.pop_back( ) removes the last element in the deque c.push_front(elem) adds a copy of elem at the front of the deque c.pop_front( ) removes the first element in the deque r.remove(val) removes all elements with the value val r.remove_if(op) removes all elements for which op(elem) is true iterators must refer to valid positions. Do not try to remove an element from an empty container. new
34
Splice Functions Linked lists have the advantage that you can insert and delete elements at any point in the list in constant time. Lists support a number of unique functions to change the order of and re-link elements in a list.
35
Splice Functions Linked lists have the advantage that you can insert and delete elements at any point in the list in constant time. Lists support a number of unique functions to change the order of and re-link elements in a list. This is accomplished by manipulating pointers
36
Operation Effect c.unique( ) removed duplicates of consecutive elements c1.splice(pos, c2) moves all elements of c2 to c1 in front of the iterator position pos c1.splice(pos, c2, c2p) moves the element at c2p to c1 in front of the iterator position pos c1.splice(pos, c2, c2b, c2e) moves all elements in the range [c2b, c2e] in c2 to c1 in front of the iterator position pos c.sort( ) sorts all elements of c using < c.sort(op) sorts all elements of c using op( ) c1.merge(c2) assuming that c1 and c2 are sorted, moves all elements of c2 into c1 so that the resulting list is still sorted
37
#include using namespace std; int main ( ) { list sentence; sentence.assign(3, string("middle stuff") ); sentence.push_back("end string"); sentence.push_front("front_string"); list ::iterator p; for (p = sentence.begin( ); p != sentence.end( ); p++) cout << *p << "\n"; cout << endl; system("PAUSE"); return 0; }
38
cout << "\n\nSorted List\n\n"; sentence.sort( ); for (p = sentence.begin( ); p != sentence.end( ); p++) cout << *p << "\n"; cout << endl;
39
Sets and Multisets Sets and multisets sort their elements automatically according to a certain sorting criteria. Multisets allow duplicate elements, while sets do not. The sorting criteria must define strict weak ordering: It has to be antisymmetric for <, if x < y is true, then y < x is false It has to be transitive for <, if x < y is true and y < z is true, then x < z is true It has to be irreflexive for <, x < x is always false
40
1 3 4 6 9 1 1 4 4 9 Set Multiset
41
5 2 4 9 7 11 8 Sets and multisets are usually stored internally as balanced binary trees. (You will learn about trees in data structures.)
42
Sets and multisets do not provide any operations for direct element access. You may not change the value of an element directly because this may affect the ordering. You have to remove the element that has the old value and insert the element with the new value.
43
Constructors OperationEffect set c A set that sorts with < operator set c A set that sorts with op multiset c A multiset that sorts with < operator multiset c A multiset that sorts with op set > collection;
44
Special Search Operations Operation Effect count (elem) returns the number of elements with value elem find (elem) returns the position of the first element with value elem
45
Inserting and Removing Elements Operation Effect c.insert(elem) inserts a copy of elem and returns the position (and for sets whether or not it succeeded) c.insert(pos, elem) inserts a copy of elem, using pos as a hint of where c.erase(elem) removes all elements of value elem c.Erase (pos) removes the element at pos c.clear( ) removes all elements from the set
46
Iterators Iterators are bidirectional, and can’t be used in algorithms the require random access. Most importantly, from the iterator’s point of view, all elements are considered constant. Thus you cannot use an iterator in any modifying algorithm on elements of a set or a multiset.
47
#include using namespace std; int main ( ) { set nums; nums.insert(17); nums.insert(3); nums.insert(12); nums.insert(6); nums.insert(3); set ::iterator p; for (p = nums.begin( ); p != nums.end( ); p++) cout << *p << "\n"; cout << endl; system("PAUSE"); return 0; }
48
note that the values are in order. and 3 only appears once.
49
Maps and Multimaps Maps and multimaps mange key/data pairs as elements and sort their contents automatically according to a certain sorting criteria that is used for the actual key.
50
2 x 1 y 4 z 5 y key value
51
Constructors Operation Effect map c A map that sorts keys with < operator map c A map that sorts keys with op multimap c A multimap that sorts keys with < operator multimap c A multimap that sorts keys with op
52
Special Search Operations OperationEffect count (k)returns the number of elements with key k find (k) returns the position of the first element with key k
53
Iterators Iterators are bidirectional, and can’t be used in algorithms that require random access. Most importantly, from the iterator’s point of view, all elements are considered constant. Thus you cannot use an iterator in any modifying algorithm on elements of a map or a multimap.
54
Maps as Associative Arrays Non-constant maps provide a subscript operator for direct element access. However, the index of the subscript operator is not the integer position of the element, but it is the key that is used to identify the element.
55
#include using namespace std; int main ( ) { map stocks; stocks["GM"] = 456.34; stocks["Ford"] = 321.87; stocks["BMW"] = 256.90; stocks["Audi"] = 123.78; map ::iterator p; for (p = stocks.begin( ); p != stocks.end( ); p++) cout first second << "\n"; cout << "\n\n" << stocks["Audi"]; cout << endl; system("PAUSE"); return 0; } key data
56
sorted by key
57
When to Use Which Container characteristic vector deque list set map internal store dynamic array array of arrays binary tree binary tree binary tree elements value value value value key/value pair random access yes yes no no no iterator category random access random access bidirectional bidirectional bidirectional search/find elements slow slow very slow fast fast for key insert/remove at the back at front & back anywhere -- -- elements insert/remove on reallocation always never never never invalidates pointers, references, & iterators
58
Container Adapters Container adapters modify the standard containers to fit special needs. Stacks Queues Priority Queues
59
Stack A stack is a first-in, last-out container. It provides the following interface: OperationEffect push( ) inserts an element into the stack pop( ) removes an element from the stack top( ) returns the top element in the stack push pop top
60
Queue A queue is a first-in, first-out container. It implements the following interface: OperationEffect push( ) inserts an element into the queue front( ) returns the next element in the queue pop( ) removes an element from the queue back ( ) returns the last element push pop back front
61
Priority Queue A priority queue is a queue from which elements are read in priority order. OperationEffect push( ) inserts an element into the queue top( ) returns the highest priority element in the queue pop( ) removes an element from the queue push pop top elements are prioritized according to their value
62
Bitsets Bitsets are fixed sized arrays of bits, or boolean values. They are useful for managing sets of flags
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.