C++ Standard Template Library. Contents. Pierre Fierz. 1 Introduction. 2 Organization of STL Header Files. Organization of STL Header Files

Size: px
Start display at page:

Download "C++ Standard Template Library. Contents. Pierre Fierz. 1 Introduction. 2 Organization of STL Header Files. Organization of STL Header Files"

Transcription

1 Contents Chapter 3 1 Lecture Advanced C Associative 5 Associative 6 Bernese University of Applied Sciences School of Engineering and Information Technology Division of Computer Science 7 Associative Why should we use the C++ STL? It is better to reuse existing code, then to rewrite it Associative The Standard uses two features of C++ that supports data independence: Templates Operator overloading With these features an algorithm can assume just very little about the actual object, which can be: Fundamental data type (int, double, char,...) User-defined data types/classes (String, Complex,...) Consequently,such an algorithm is not confined to a specific data type, and it has a higher reusability potential than does a type-dependent algorithm. Associative 7 Associative The Standard (STL) is an exemplary framework that is built on the foundations of generic programming

2 (2) STL is a collection of generic algorithms and containers The communication between containers and algorithms is done through iterators STL components are grouped together under the namespace std We have the following groups of STL components: Numeric libraries Utilities String... Associative Associative Associative (2) Container classes are repositories for different kind of data types in different storing ways Header <vector> <list> <deque> <queue> <stack> <map> <multimap> <set> <multiset> <bitset> Contents An array of T A doubly-linked list of T A double-ended queue of T A queue of T A stack of T An associative array of T with unique keys An associative array of T A set of T A bag of T A set of Boolean values Associative STL generic algorithms can be applied to a sequence of elements. They are defined in the following header file. Header <algorithm> Contents A collection of generic algorithms are used to navigate sequences. They are defined in the following header file. Header <iterator> Contents Various types of iterators and iterator support Associative

3 (3) STL provides several classes and algorithms that are specifically designed for numeric computations (see the following table). 1 Header <complex> <valarray> <numerics> Contents Complex numbers and their associated operations Mathematical vectors and their associated operations Generalized numeric operations The headers in the following table define auxiliary components that are used in STL containers and algorithms. These include function adaptors, pairs, and class auto_ptr (discussed later). Associative Associative Header <utility> <functional> <memory> Contents Operators and pairs Function objects Allocators and auto_ptr 7 Associative (2): Sequence A container can hold objects A container is not confined to a specific type, it can store objects of any kind In the old C era, the only container is the well known built-in array These built-in array are inherited into C++, the corresponding STL container is the vector which provide random access and can store any type of data Arrays doesn t allow to insert new elements in the middle of the array Furthermore, they don t allow to append elements at the end of the array (fixed size) Other data models (e.g. lists) allow to add elements in the middle or to append new elements at the front or the end Associative A sequence container organizes a collection of objects of the same type T into a strictly linear arrangement. Following are examples of sequence containers: T v[n ] A built-in array that stores a fixed number of n elements and provides random access to them. std::vector<t> An array-like container that stores a varying number of n elements and provides random access to them. Insertions and deletions at the end of a vector are constant time operations. std::deque<t> A double-ended queue that provides random access to a sequence of varying length, with constant time insertions and deletions at the beginning and the end. std::list<t> A list that provides linear time access to a sequence of varying length, with constant time insertions and deletions at any position. Associative

4 (3): Sequence (4): Vector The vector container type is very similar to an array To choose a container, decide what sort of operations you will most frequently perform on your data, then use the following table to help you. Operation vector deque list Access first element Constant Constant Constant Access last element Constant Constant Constant Access random element Constant Constant Linear Add/Delete at beginning Linear Constant Constant Add/Delete at end Constant Constant Constant Add/Delete at random Linear Linear Constant Associative The random access is possible as in normal array. The time overhead for reading is constant (order O(1)) my_vector[2] = 3; a = my_vector[7]; Manipulating (add / delete) at the end of the vector is cheap Bounds are not checked automatically!! Insertions or deletions anywhere not at the end adds a linear time overhead (order O(N), N elements in vector) Shuffling around is necessary Memory overhead is low, comparable to a normal array Associative (5): vector (5): vector The table below shows some of the main vector functions. The table below shows some of the main vector functions. Interface Vector Interface Vector begin() end() Returns iterator pointing to first element Returns iterator pointing after last element push_back(...) Add element to end of vector pop_back(...) Destroy element at end of vector Associative Associative

5 (5): vector (5): vector The table below shows some of the main vector functions. The table below shows some of the main vector functions. Interface Vector Interface Vector push_back(...) Add element to end of vector pop_back(...) Destroy element at end of vector swap(, ) Swap two elements insert(, ) Insert new element Associative push_back(...) Add element to end of vector pop_back(...) Destroy element at end of vector swap(, ) Swap two elements insert(, ) Insert new element size() Number of elements in vector capacity() Capacity before more memory is needed empty() True if vector is empty Associative (5): vector The table below shows some of the main vector functions. Interface Vector push_back(...) Add element to end of vector pop_back(...) Destroy element at end of vector swap(, ) Swap two elements insert(, ) Insert new element size() Number of elements in vector capacity() Capacity before more memory is needed empty() True if vector is empty [] Random access operator at() Random access operator with bound check Associative (6): double-ended queue The double-ended queue, deque has similar properties to a vector Additional feature for adding and deleting elements at both ends Random read access exists like in vector The deque is (like the vector also) not very good at inserting or deleting elements at random positions Associative

6 (6): double-ended queue The double-ended queue, deque has similar properties to a vector Additional feature for adding and deleting elements at both ends Random read access exists like in vector The deque is (like the vector also) not very good at inserting or deleting elements at random positions Interface Double-Ended Queue (6): double-ended queue The double-ended queue, deque has similar properties to a vector Additional feature for adding and deleting elements at both ends Random read access exists like in vector The deque is (like the vector also) not very good at inserting or deleting elements at random positions Interface Double-Ended Queue Associative push_front(...) Add element to front of deque pop_front(...) Destroy element at front of deque Associative (6): double-ended queue The double-ended queue, deque has similar properties to a vector Additional feature for adding and deleting elements at both ends Random read access exists like in vector The deque is (like the vector also) not very good at inserting or deleting elements at random positions Interface Double-Ended Queue (6): double-ended queue The double-ended queue, deque has similar properties to a vector Additional feature for adding and deleting elements at both ends Random read access exists like in vector The deque is (like the vector also) not very good at inserting or deleting elements at random positions Interface Double-Ended Queue push_front(...) Add element to front of deque pop_front(...) Destroy element at front of deque push_back(...) Add element to end of deque pop_back(...) Destroy element at end of deque Associative push_front(...) Add element to front of deque pop_front(...) Destroy element at front of deque push_back(...) Add element to end of deque pop_back(...) Destroy element at end of deque swap(, ) Swap two elements insert(, ) Insert new element Associative

7 (6): double-ended queue The double-ended queue, deque has similar properties to a vector Additional feature for adding and deleting elements at both ends Random read access exists like in vector The deque is (like the vector also) not very good at inserting or deleting elements at random positions Interface Double-Ended Queue (6): double-ended queue The double-ended queue, deque has similar properties to a vector Additional feature for adding and deleting elements at both ends Random read access exists like in vector The deque is (like the vector also) not very good at inserting or deleting elements at random positions Interface Double-Ended Queue push_front(...) Add element to front of deque pop_front(...) Destroy element at front of deque push_back(...) Add element to end of deque pop_back(...) Destroy element at end of deque swap(, ) Swap two elements insert(, ) Insert new element size() Number of elements in deque capacity() Element capacity before more memory needed empty() True if deque is empty Associative 3.16 push_front(...) Add element to front of deque pop_front(...) Destroy element at front of deque push_back(...) Add element to end of deque pop_back(...) Destroy element at end of deque swap(, ) Swap two elements insert(, ) Insert new element size() Number of elements in deque capacity() Element capacity before more memory needed empty() True if deque is empty [] Random access operator at() at() Random access operator with bound check Associative 3.16 (7): List List containers doesn t provide a random access operator (no []) Lists are suited to add or delete elements randomly in the list Implemented as double-linked list structure and support bidirectional iterators (7): List List containers doesn t provide a random access operator (no []) Lists are suited to add or delete elements randomly in the list Implemented as double-linked list structure and support bidirectional iterators Interface List Associative Associative

8 (7): List (7): List List containers doesn t provide a random access operator (no []) Lists are suited to add or delete elements randomly in the list Implemented as double-linked list structure and support bidirectional iterators Interface List List containers doesn t provide a random access operator (no []) Lists are suited to add or delete elements randomly in the list Implemented as double-linked list structure and support bidirectional iterators Interface List push_front(...) Add element to front of list pop_front(...) Destroy element at front of list Associative push_front(...) Add element to front of list pop_front(...) Destroy element at front of list push_back(...) Add element to end of list pop_back(...) Destroy element at end of list Associative (7): List (7): List List containers doesn t provide a random access operator (no []) Lists are suited to add or delete elements randomly in the list Implemented as double-linked list structure and support bidirectional iterators Interface List List containers doesn t provide a random access operator (no []) Lists are suited to add or delete elements randomly in the list Implemented as double-linked list structure and support bidirectional iterators Interface List push_front(...) Add element to front of list pop_front(...) Destroy element at front of list push_back(...) Add element to end of list pop_back(...) Destroy element at end of list swap(, ) Swap two elements erase(...) Delete elements insert(, ) Insert new element Associative push_front(...) Add element to front of list pop_front(...) Destroy element at front of list push_back(...) Add element to end of list pop_back(...) Destroy element at end of list swap(, ) Swap two elements erase(...) Delete elements insert(, ) Insert new element size() Number of elements in list capacity() Element capacity before more memory needed empty() True if list is empty Associative

9 (7): List List containers doesn t provide a random access operator (no []) Lists are suited to add or delete elements randomly in the list Implemented as double-linked list structure and support bidirectional iterators Interface List push_front(...) Add element to front of list pop_front(...) Destroy element at front of list push_back(...) Add element to end of list pop_back(...) Destroy element at end of list swap(, ) Swap two elements erase(...) Delete elements insert(, ) Insert new element size() Number of elements in list capacity() Element capacity before more memory needed empty() True if list is empty sort() Specific function because <algorithm> sort routines expect random access iterators Associative 3.17 (8): Accessing single Elements Two different methods for accessing single elements in vectors and queues exist. The overloaded subscript operator [], or the member function at() for direct access to a vector s element. Both exist in a const and a non-const version The overloaded subscript operator [] Efficient (normally inline) No range check performed (dangerous) The member function at() Less efficient Range check is performed, throws an exception (std::out_of_range) in case of out-of-bound access int main() { using namespace std; vector<string> vs; // vs has no elements currently vs.push_back( "string" ); // add first element vs[0] = "overriding string"; // override it using [] try { cout << vs.at(10) << endl; // exception: out of range catch( std::out_of_range& except ) { // handle out-of-range subscript Associative 3.18 (9): Front and Back Operations Front and back operations refer to the beginning and the end of a container, respectively. The member function push_back() appends a single element to the end of the container. When the it reallocates additional storage, and then appends the element. The member function pop_back() removes the last element from the container. The member functions front() and back() access a single element at the container s beginning and end, respectively. int main() { using namespace std; Associative Associative vector<short> v; v.push_back( 5 ); v.push_back( 10 ); cout << "front: " << v.front() << endl; // 5 cout << "back: " << v.back() << endl; // 10 v.pop_back(); // remove v[1], // which is 10 cout << "back: " << v.back() << endl; // now Associative 3.20

10 (2): begin() and end() Every container posseses the two functions begin() and end() An iterator is an abstraction of a pointer to an element of a container. The fundamental concepts of an iterator are: Return the value of the element which it points to (dereferencing represented by the operators * and >) Point to the next element (increment represented by the operator ++) Compare two pointers (represented by the operator ==) The begin() method returns an iterator that points to the first element of a container The end() method returns an iterator that points one position past the last element of the container Can be seen as a pointer to the null-character \0 of a null-terminated string This allows easy usage for looping through a container The datatype int* is an iterator for the datatype int[]. The class list<int>::iterator is an iterator for the class list<int> Associative vector<int> v; int n = 0; for (vector<int>::iterator p = v.begin(); p =! v.end(); p++) { std::cout << *p << std::endl; Associative Const and non-const version of the iterators exist A reverse version of the iterators also exists (rbegin() and rend(), the y return reverse iterators (3): Iterator categories (4): Iterator categories There are five different iterator categories Input permit only read accesses and can only be moved forward sequentially. An element can only be read once. An example is an iterator reading characters from the keyboard. Output permit only write accesses and can only be moved forward sequentially. An example is an iterator writing characters to the standard output. Forward are a combination of input and output iterators. They can only be moved forward sequentially, now however reading and writing are allowed. Bidirectional extends the abilities of the forward by the possibility to be moved backward sequentially. Random Access are the most flexible iterators. They cannot only be moved sequentially, they also permits a direct access to any position in a given range. Associative 3.23 The following table shows, which operators are implemented for the different iterator categories. Iterator operators output input forward bidirectional random-access read =*p =*p =*p = *p access > > > >, [] write *p= *p= *p= *p= iterate , ++,, +,, +=, -= compare ==,!= ==,!= ==,!= ==,!=, <, >, <=, >= Associative 3.24

11 (5): and Generic are a generalization of pointers, abstracting from their requirements in a way that allows a C++ program to work with different data structures in a uniform manner. act as intermediaries between containers and generic algorithms. Instead of operating on specific data types, algorithms are defined to operate on a range specified by a type of iterator. Any data structure that satisfies the requirements of the iterator may then be operated on by the algorithm. There are many examples of generic algorithms using iterators. Here are some examples sort sort a range into ascending order find find a value in a given range for_each apply a function to a range of elements set_union computes the union of two sets copy copy some range of elements to a new location remove remove elements equal to certain value Associative (6): Invalidation of STL are not secure in the sense that they can be or become invalid. There are several categories of invalid iterators. singular iterators past-the-end iterators out-of-range iterators dangling iterators inconsistent iterators We will formulate some rules for working with iterators Associative (7): Invalidation of STL (8): Invalidation of STL : Singular Quote from the standard Rule 1 Never use invalid iterators. result of using invalid iterators is undefined expressions such as *iter, ++iter, etc. exhibit undefined behavior which can be anything from returning a valid and useful result to a program crash or reformatting of your hard-disk Associative can have singular values that are not associated with any container. Results of most expressions are undefined for singular values the only exception is an assignment of a non-singular value to an iterator that holds a singular value. In this case the singular value is overwritten the same way as any other value. s: Singular uninitialized pointers int* ptr default-constructed container iterators list<int>::iterator iter; default-constructed iterator adapters reverse_iterator<int*> riter dereferenceable and past-the-end values are non-singular Associative

12 (9): Invalidation of STL : Singular (10): Invalidation of STL : Singular singular iterators can be created singular iterators can be used inadvertently as input or output iterators int array[100]; int* begin, end; list<int> lst; list<int>::iterator out; copy(begin, end, out); //singular iterators Associative singular iterators are not associated with any container only assignment is defined results of most expressions are undefined for singular iterators only assignment of a non-singular iterator to a singular iterator is valid Rule 2 Never perform any operation on a singular iterator except assignment of a non-singular iterator Associative (11): Invalidation of STL : Past-the-End (11): Invalidation of STL : Past-the-End s: non-dereferenceable past-the-end iterators Quote from the standard Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding container. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable. additional requirement in the standard: that can be incremented must be dereferenceable. Associative non-dereferenceable past-the-end iterators end-of-container iterator container.end() end-of-array iterator array+size end-of-input-stream iterator istream_iterator<t>() reverse past-the-end iterator container.rend() reverse end-of-array iterator reverse_iterator<elemt*>(array) : dereferenceable past-the-end iterator int arr[500];... int* where = find(arr,arr+100,5); //where++ is dereferenceable Associative

13 (12): Invalidation of STL : Past-the-End past-the-end iterators can be created past-the-end iterators can be used inadvertently as input or output iterators int array[100]; list<int> lst; copy(array,array+100,lst.begin()); //past-the-end iterator (13): Invalidation of STL : Out-of-Range Out-of-range iterators are iterators that have been advanced beyond the range of valid elements contained in a sequence. beyond the past-the-end iterator of the sequence via incrementing or pointer arithmetics beyond the beginning of the sequence via decrementing or pointer arithmetics The result of any operation on an out-of-range iterators is undefined. out-of-range iterators can inadvertently be created often implicitly inside an algorithm list is empty = begin iterator equals end iterator Rule 3 Never dereference or increment the past-the-end iterator of an iterator range. Associative 3.33 istream_iterator<string> in(cin),eof; vector<string> vec; vec.reserve(100); copy(in,eof,vec.begin()); //might be advanced beyond capacity algorithm might advance iterator beyond capacity unpredictable result: memory corruption without program crash Associative 3.34 (14): Invalidation of STL : Out-of-Range (15): Invalidation of STL : Out-of-Range out-of-range iterators can be created inadvertently whenever size of sequence is determined by information other than the sequence itself all algorithms that take output iterator size of output sequence determined by size of input sequence copy(), remove_copy_if(), transform(), merge(),... algorithms with more than one input sequence size of 2nd input sequence determined by size of 1st input sequence equal(), transform() Associative avoid problem: use inserters as output destination insert iterators have no valid range can be incremented infinitely often Rule 4 istream_iterator<string> in(cin),eof; vector<string> vec; back_insert_iterator<std::vector<string> > vecit(vec); copy(in, eof, vecit); //cannot be advanced beyond capacity Associative Prefer inserters as output destinations over regular iterators

14 (15): Invalidation of STL : Dangling (16): Invalidation of STL : Dangling lifetime dependencies are frequently overlooked invalidation through operations is even less obvious A dangling iterator points to a sequence element : stream iterators depend on the stream that does not exists or was moved to a different memory location or is otherwise not accessible All operations on dangling iterators exhibit undefined behavior Dangling iterators can inadvertently be created due to lifetime dependencies due to operations that invalidate iterators Associative istream_iterator<string> in(ifstream( in.txt")), eof; ostream_iterator<string>(cout, \n ) out; copy(in, eof, out); //"in" is dangling iterator problem: lifetime of temporary stream object ceases at end of statement file closed dangling iterator possible results: program crash Associative Rule 5 Never use temporary stream objects in conjunction with stream iterators (17): Invalidation of STL : Dangling (18): Invalidation of STL : Dangling reallocation of a vector s internal array invalidates all iterators pointing to the vector reallocation can be triggered by iterators are pointer-like objects introduce the same lifetime dependencies as pointers sequence must live longer than iterator all operations on dangling iterators are illegal usually (but not always) lead to a program crash insert(), push_back() resize(), reserve() vector<int> v(10); Rule 6 are pointers. Keep an eye on lifetime dependencies between iterator and container. Associative p = v.begin(); for (int i = 0; i < 100; i++) { v.push_back(i); // p is dangling here Associative Rule 7 Don t re-use iterators pointing to elements in a vector after any calls to insert(), push_back(), resize() or reserve()

15 (19): Invalidation of STL : Inconsistent Inconsistent iterators are iterators that return unexpected values when they are dereferenced. can happen as a side-effect of erase() and insert() on vector or deque can be the result of a modifying algorithm Dereferencing an inconsistent iterator is invalid in the sense that it yields unexpected results. : Inconsistent iterator after modifying algorithm string arr[500];... fill with elements... string* where = find(arr,arr+500, Tom ); sort(arr,arr+500); cout << *where << endl; //need not print: Tom : Inconsistent iterator after erase() Associative (20): Invalidation of STL : Inconsistent Inconsistent iterators happen as side effect of container operations insert() and erase() on vector and deque modifying algorithms Rule 8 inplace algorithms (modify input sequence) remove(), sort(), partition(), replace(),... copy algorithms (modify output sequence) remove_copy(), transform(), merge(),... Don t re-use iterators pointing to elements in a container after any calls to insert(), erase() or to modifying algorithms. Associative vector<string> vec(arr,arr+500); vector<string>::iterator where = find(vec.begin(),vec.end(), Tom ); vec.erase(vec.begin(),where); cout << *where << endl; //need not print: Tom STL provides a rich collection of generic algorithms 3 Applicable on containers and other sequences 4 5 Associative Three major categories exist: non-modifiying sequence operations mutating sequence operations sorting algorithms Associative 6 7 Associative

16 (2): Non-modifying sequence operations (3): Non-modifying sequence operations of the find() algorithm Non-modifying sequence operations do not modify the sequence on which they operate They provide: search for elements check for equality / unequality /... counting of elements... Associative It searches for an element in a given sequence Returns an iterator to the found element Returns iterator to one-past last element, like end(), if element couldn t be found Takes three arguments Iterator pointing to the beginning of the sequence Iterator pointing to the end of the sequence (one past last element!) The value to be matched Associative (4): Non-modifying sequence operations (5): Mutating Sequence Operations Find in a List or an Array #include <algorithm> // definition of find() #include <list> #include <iostream> using namespace std; int main() { char lc1[] = { A, T, L ; // Initialize a list with the same elements list<char> lc(lc1, lc1+3); // find A in the list list<char>::iterator p = find( lc.begin(), lc.end(), A ); // find A in the array char* p1 = find(lc1, lc1+3, A ); // was A found? if(p!= lc.end()) *p = S ; // then replace it with S if(p1!= lc1 + 3) *p1 = S ; // then replace it with S Associative Mutating sequence operations modify the sequence on which they operate We have for example: copy fill replace transform... Associative while(p!= lc.end()) cout << *p++; cout << endl; while( p1!= lc1+3 ) cout << *p1++; cout << endl; // display the modified list // Output: STL // display the modified array // Output: STL

17 (6): Mutating Sequence Operations (7): Mutating Sequence Operations of the copy() algorithm It provides a generic copy function Copies a sequence of objects to a specific target Returns an iterator pointing to the one-past the last element copied Takes three arguments Iterator pointing to the beginning of the sequence to be copied Iterator pointing to the end of the sequence (one past last element!) Output iterator pointing to the first element of the destination range The destination range must have enough space to get the copy If possible use an insert iterator Associative 3.49 copy with normal iterator #include <algorithm> #include <list> #include <vector> using namespace std; int main(){ list<int> li; vector <int> vi; for (int i = 1; i <= 10; i++) li.push_back(i); // must make room for copied elements in advance vi.resize( li.size() ); // copy list elements into vector, starting at vector s beginning copy(li.begin(), li.end(), vi.begin()); copy with insert iterator int main(){ list<int> li; vector <int> vi; for (int i = 1; i <= 10; i++) li.push_back(i); copy(li.begin(), li.end(), back_insert_iterator<vector<int> >(vi)); Associative 3.50 (8): Sorting algorithms (9): Sorting algorithms of the sort() algorithm This category contains algorithms for sorting and merging sequences We have for example: sort partial_sort binary_search lower_bound... Associative Provides a generic sorting algorithm Sorts the elements in a given range (default is ascending order) No return Takes two arguments, optionally three Iterator pointing to the beginning of the sequence to be sorted Iterator pointing to the end of the sequence (one past last element!) to be sorted Optional predicate argument that is a pointer to a binary-returning predicate function (less-than) Associative Descending order sorting can be done by using the reverse iterators

18 (10): Sorting algorithms (11): Sorting algorithms example: sorting a sequence #include <iostream> #include <algorithm> //definition of sort() #include <vector> #include <cstdlib> using namespace std; int main() { vector <int> vi; for(int i = 0; i < 40; i++) vi.push_back(rand()%200); // sort vi; default is ascending order sort(vi.begin(), vi.end()); for(int i = 0; i < 40; i++) cout << vi[i] << ", "; cout << endl; Associative The sorting algorithm has some requirements to the container elements: The relational operators == and < must exist User-defined types without these operators can use containers, but cannot use the sort algorithm. In this case the user can supply a less_than function. example: sort algorithm with user defined order // Compare Function to sort int s in descending order bool less_than(int a, int b) { return b<a; int main() { vector <int> vi; for(int i = 0; i < 40; i++) vi.push_back(rand()%200); Associative // Now sort in descending order sort(vi.rbegin(), vi.rend()); for(int i = 0; i < 40; i++) cout << vi[i] << ", "; cout << endl; // sort vi; in descending order sort(vi.begin(), vi.end(), less_than); for(int i = 0; i < 40; i++) cout << vi[i] << ", "; cout << endl; (12): How to Create a Generic Algorithm The creation of a generic algorithm can be done through different steps As an example, we want to evolve a generic binary search algorithm out of a conventional one. The starting point is a C++ binary search algorithm for integer Arrays. (13): How to Create a Generic Algorithm Assumptions binary_search makes about its environment: The elements of the array must be integers. To make it work with arrays of arbitrary types we transform binary_search in a template function. Also in case of an unsuccessful search we return the pointer array + n (a past-the-end pointer!) instead of null. const int* binary_search( const int* array, int n, int x ) { const int* lo = array, *hi = array + n, *mid; while( lo!= hi ) { mid = lo + (hi - lo) / 2; if( x == *mid ) return mid; if( x < *mid ) hi = mid; else lo = mid + 1; return 0; Associative template<class T> const T* binary_search(const T* array, int n, const T& x ) { const T* lo = array, *hi = array + n, *mid; while( lo!= hi ) { mid = lo + (hi - lo) / 2; if( x == *mid ) return mid; if( x < *mid ) hi = mid; else lo = mid + 1; return array + n; Associative

19 (14): How to Create a Generic Algorithm (15): How to Create a Generic Algorithm Instead of handing over array as pointer to the first element and a size, we could also specify a pointer to the first and past the last element to approach STL s iterator concept. The last step is to change from pointers to iterators Since binary_search needs a random-access iterator we will name the type of first and last RandomAccessIterator. template<class T> const T* binary_search(t* first, T* last, const T& x ) { T* not_found = last, *mid; while(first!= last) { mid = first + (last - first) / 2; if( x == *mid ) return mid; if( x < *mid ) last = mid; else first = mid + 1; return not_found; Associative template<class RandomAccessIterator, class T> const RandomAccessIterator binary_search(randomaccessiterator first, RandomAccessIterator last, const T& x ) { RandomAccessIterator not_found = last, mid; while(first!= last) { mid = first + (last - first) / 2; if( x == *mid ) return mid; if( x < *mid ) last = mid; else first = mid + 1; return not_found; Associative (16): How to Create a Generic Algorithm The only assumptions the algorithm makes are: the random access to elements of type T between the two iterators and that operator== and operator< are defined for type T and the value type of the iterator. The algorithm hasn t lost anything of its functionality, especially not when dealing with built in types int main() { int array[high]; int search;... Fill the array... Associative 4 5 Associative vector<int> vec(array, array + HIGH); // Search in array const int* p = binary_search(ar, ar + HIGH, search); // Search in vector vector<int>::iterator it; it = binary_search(v.begin(), v.end(), search); 6 7 Associative

20 (2) The next examples shows how Functors may be used : Generic binary search Callback functions can be invoked by using function pointers (old style, C) OO environments accept functions encapsulated in a function object (also called Functor) Functors are more resilient, the object can be modified without affecting its users Compilers can inline functors (nearly impossible with function pointers) Functors can be generic, they can embody generic algorithms by means of member templates Function objects are discussed in more details in a separate chapter (usage also outside of STL) Associative template<class RandomAccessIterator, class T, class F> const RandomAccessIterator binary_search(randomaccessiterator first, RandomAccessIterator last, const T& x, F less) { RandomAccessIterator not_found = last, mid; while(first!= last) { mid = first + (last - first) / 2; if(less(x, *mid)) last = mid; else if (less(*mid, x)) first = mid + 1; else return mid; return not_found; class Less { public: bool operator()(int a, int b) { return a < b; ; Associative it = binary_search(v.begin(), v.end(), search, Less()); Associative 1 2 Associative containers are also called Associative arrays 3 They can use index, which need not to be an integer An associative array is also called map or dictionary 4 C++ STL defines several associative arrays: 5 6 Associative map multimap set multiset Associative 7 Associative

21 Associative (2): Map The map can be seen as a sort of vector or deque Two main differences exist: The index values (also called key values) needn t to be integers, but can be any ordered data type The map can be indexed by real numbers for example The key value must be a data type that has a comparison operator Elements can be accessed through the subscript operator or through any other known accessing technique The map is an ordered structure Elements are kept in a sequence, the ordering is determined by the key value Retrieves rapidly the elements (logarithmic time, ordered structure) No limit in size (varies like lists) Map is a set that maintains a collection of pairs The map data structure demands unique key values One-to-one association between key element and corresponding value Adding a new element with an existing key is ignored! Associative Associative (3): Map The map is a template data structure that is specialized by Type of the key elements Type of the associated elements Operator used in comparing key (optional) /* * map indexed by doubles containing strings */ map<double, string, less<double> > map_one; /* * map indexed by integers, containing integers Associative * map is initialized by elements form "acontainer"\usepackage{pgfpages \pgfpagesuselayout{4 on 1[a4paper,landscape,border shrink=5mm] */ map<int, int> map_two(acontainer.begin(), acontainer.end()); /* * create a new map, initializing it from map two */ map<int, int> map_three(map_two); Associative (4): Map Type Definitions Associative (5): Map Type Definitions Map and multimap include a number of type definitions Type key_type value_type mapped_type iterator const_iterator reverse_iterator const_reverse_iterator reference const_reference size_type key_compare value_compare difference_type allocator_type Definition The type associated with the keys used to index the map. The type held by the container, a key/value pair. The type associated with values. A Bidirectional iterator An iterator that does not allow modification of the underlying sequence. An iterator that moves in a backward direction. A combination constant and reverse iterator. A reference to an underlying value. A reference to an underlying value that will not permit the element to be modified. An unsigned integer type, used to refer to the size of containers. A function object that can be used to compare two keys. A function object that can be used to compare two elements. A signed integer type, used to describe the distances between iterators. An allocator used by the container for all storage management. Associative : Usage of map types // Defining a map indexed by ints containing strings map<int, string> mymap; // Defining an iterator for a map indexed by ints containing strings map<int, string>::iterator it; // Define an Element of the map. This is a pair map<int, string>::value_type element(2, "Hello world"); mymap.insert(element); cout << element.first << ", " << element.second << endl; // Define the compare operator for the map map<int, string>::key_compare comp; if(comp(i, j)) cout << "element i is less than j" << endl; Associative

22 Associative (6): Insert and Access Elements in a Map Values can be inserted into a map by using the insert() operation The subscript operator can also be used for insertion of new elements The subscript operator can also be used to access the elements Warning: Accessing a nonexistent element will create this element. int main() { map<string, string> amap; pair<map<string, string>::iterator, bool> ret; /* * Insert elements with "insert()" */ ret = amap.insert( map<string, string>::value_type("pierre", "Fierz")); ret = amap.insert( map<string, string>::value_type("pierre", "Müller")); if (!ret.second) { cout << "Element: " << ret.first->first << " already in map with value: " << ret.first->second << endl; Associative 3.69 Associative (7): Insert and Access Elements in a Map : continue /* * Insert element with subscript operator [] */ amap["jacques"] = "Boillat"; /* * Access element with [] */ cout << amap["jacques"] << endl; string s = amap["hans"]; // creates a new element with value "" map<string, string>::iterator it = amap.begin(); while (it!= amap.end()) cout << (it++)->first << ", "; // output: Hans, Jacques, Pierre, cout << endl; /* * Remove "Hans from the map */ amap.erase("hans"); it = amap.begin(); while (it!= amap.end()) cout << (it++)->first << ", "; // output: Jacques, Pierre, cout << endl; Associative 3.70 Associative (8): Multimap Associative (9): Set In a multimap a key can occur more than once. The subscript operator [] is not defined for multimaps. The erase(k) function deletes all elements with the given Key k. The function count(k) returns the number of elements with key k in the map. Insert is always successfull. Valid for set and multiset Insertion or removal does not invalidate iterators The key of an element is constant and can t be modified. The value of an element can be modified. Multiple operations using (multi)maps are provided by the STL Searching Counting Element comparison for_each(), adjacent_find(), accumulate(),... Associative A set is a collection of value The set is an ordered container Comparable with a list, except the ordering Comparable with a map, but the element is also the key Optimized for insertion and removal of elements (logarithmic number of steps) Also optimized for set operations (O(n log(n))) Not size limited, expands and shrinks dynamically In the set The element is the key The element is unique In the set, the insertion of an existing element is ignored! Associative

23 Associative (10): Set constructor Associative (11): Insert and Erase in Sets The set is a template data structure that is specialized by Type of the elements (which are also the key) Operator used to compare keys (optional). If not provided, the element type s less-than operator is used The element type must recognize both Equality testing operator == Less-than comparison operator < A set can be declared with no initial elements (empty) initialized from another container providing a pair of iterators //An empty set containing strings set<string, less<string> > set_one; Associative Values can be inserted into sets uniquely by using the insert() operation The method returns a pair of values An iterator pointing to the element Boolean, true if the element was inserted, else false Already existing elements won t be inserted in sets Subscript operator does not exist for sets; The erase() operation removes the elements from the set Underlying objects are cleanly destroyed with its class destroyer method Associative // A set containing int, initialized with a range of another set set<int> set_two(acontainer.begin(), acontainer.end()); //create a new set, initializing it from set two set<int> set_three(set_two); Existing elements can not be modified directly Would need a resorting of the set If an existing element must be modified, then remove the old element and add the new element Associative (12): Insert and Erase in Sets Associative (13): Set operations int main() { set<int> s1; pair<set<int>::iterator, bool> p; int aset[] = {7, 5, 3, 11, 17, 19, 13, 2, 4, 6; int *it = aset; /* * Insert some elements in the set */ p = s1.insert(1); p = s1.insert(2); p = s1.insert(1); if (!p.second) { cout << "Element: " << *(p.first) << " already exists" << endl; s1.insert(it, it + 10); set<int>::iterator it1 = s1.begin(); while (it1!= s1.end()) { cout << *it1 << ", "; ++it1; cout << endl; // output: 1, 2, 3, 4, 5, 6, 7, 11, 13, 17, 19, /* * Erase some elements */ s1.erase(39); // element doesn t exist => No effect s1.erase(17); // element 17 erased Associative 3.75 find() and count() are member functions and can be used to test if an element is in a set. empty() is a member function wich tests if the set is empty. int main() { int aset[] = {7, 5, 3, 11, 17, 19, 13, 2, 4, 6; set<int> s1(aset, aset + 10); set<int> s2; set<int>::iterator it = s1.find(19); if (it!= s1.end()) cout << *it << endl; //output: 19 if (s1.count(5) == 1) cout << "Element 5 is in set" << endl; if (s2.empty()) cout << "s2 is the empty set" << endl; Associative 3.76

24 Associative (14): Set operations Associative (15): Set operations Most set operations are implemented as algorithms. includes() can be used to test if a set is a subset of another set All set construction operators are provided. set_union() set_intersection() set_difference() set_symmetric_difference() The set construction functions take all the same kind of arguments The first two argument delimit the first set The third and fourth argument delimit the second set The fifth element is an insert iterator, were the result will be put Associative int main() { int aset1[] = {2, 3, 4, 5, 6, 7, 11, 13, 17, 19; set<int> s1(aset1, aset1 + 10); int aset2[] = {1, 2, 11, 19, 23, 27, 33; set<int> s2(aset2, aset2 + 7); set<int> s3; set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), insert_iterator<set<int> >(s3, s3.begin())); for (set<int>::iterator p = s3.begin(); p!= s3.end(); ++p) cout << *p << ", "; cout << endl; //output: 1, 2, 3, 4, 5, 6, 7, 11, 13, 17, 19, 23, 27, 33, s3.clear(); set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), insert_iterator<set<int> >(s3, s3.begin())); for (set<int>::iterator p = s3.begin(); p!= s3.end(); ++p) cout << *p << ", "; cout << endl; //output: 2, 11, 19, s3.clear(); set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), insert_iterator<set<int> >(s3, s3.begin())); for (set<int>::iterator p = s3.begin(); p!= s3.end(); ++p) cout << *p << ", "; cout << endl; //output: 3, 4, 5, 6, 7, 13, 17, s3.clear(); set_symmetric_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), insert_iterator<set<int> >(s3, s3.begin())); for (set<int>::iterator p = s3.begin(); p!= s3.end(); ++p) cout << *p << ", "; cout << endl; //output: 1, 3, 4, 5, 6, 7, 13, 17, 23, 27, 33, Associative Associative (16): Multiset Multisets are associative containers with the same properties as set containers, but allowing for multiple keys with equal values. Differences in operations between sets and multisets : count() returns the number of times the element appears in the container. erase() removes all elements with the given key. set_union() of two multisets. s 1 s 2 = {x (x s 1 x s 2 ) count(s 1 s 2, x) = max(count(s 1, x), count(s 2, x)) set_intersection() of two multisets Associative s 1 s 2 = {x x s 1 x s 2 count(s 1 s 2, x) = min(count(s 1, x), count(s 2, x)) set_difference() of two multisets s 1 \ s 2 = {x x s 1 count(s 1, x) > count(s 2, x) count(s 1 \ s 2, x) = count(s 1, x) count(s 2, x) 3.79

STL: C++ Standard Library

STL: C++ Standard Library STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms

More information

Template based set of collection classes STL collection types (container types)

Template based set of collection classes STL collection types (container types) STL Collection Types Template based set of collection classes STL collection types (container types) Sequences vector - collection of elements of type T list - doubly linked list, only sequential access

More information

Chapter 5. The Standard Template Library.

Chapter 5. The Standard Template Library. Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,

More information

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides. Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard

More information

Standard Library Reference

Standard Library Reference Standard Library Reference This reference shows the most useful classes and functions in the standard library. Note that the syntax [start, end) refers to a half-open iterator range from start to end,

More information

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11 Di erent Kinds of Containers Container Notes A container is an object that stores other objects and has methods for accessing the elements. There are two fundamentally di erent kinds of containers: Sequences

More information

Standard Template Library

Standard Template Library Standard Template Library Wednesday, October 10, 2007 10:09 AM 9.3 "Quick Peek" STL history 1990s Alex Stepanov & Meng Lee of HP Labs 1994 ANSI/IS0 standard Components Container class templates Iterators

More information

Lecture-5. STL Containers & Iterators

Lecture-5. STL Containers & Iterators Lecture-5 STL Containers & Iterators Containers as a form of Aggregation Fixed aggregation An object is composed of a fixed set of component objects Variable aggregation An object is composed of a variable

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing STL and Iterators Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer Semester

More information

SSE2034: System Software Experiment 3

SSE2034: System Software Experiment 3 SSE2034: System Software Experiment 3 Spring 2016 Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu STL Collection Types Template based set of collection

More information

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures C++ Review 1 Purpose of Review Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures 2 Class The Class defines the data structure

More information

Programming in C++ using STL. Rex Jaeschke

Programming in C++ using STL. Rex Jaeschke Programming in C++ using STL Rex Jaeschke Programming in C++ using STL 1997, 1999, 2002, 2007, 2009 Rex Jaeschke. All rights reserved. Edition: 2.0 All rights reserved. No part of this publication may

More information

CS11 Advanced C++ Fall Lecture 1

CS11 Advanced C++ Fall Lecture 1 CS11 Advanced C++ Fall 2006-2007 Lecture 1 Welcome! ~8 lectures Slides are posted on CS11 website http://www.cs.caltech.edu/courses/cs11 ~6 lab assignments More involved labs 2-3 week project at end CS

More information

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland May 6, 2010 ENGI

More information

19.1 The Standard Template Library

19.1 The Standard Template Library Chapter 19: The Template Library From a review of Effective STL : 50 Specific Ways to Improve Your Use of the Standard Template Library by ScottMeyers: It s hard to overestimate the importance of the Standard

More information

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed

More information

CS197c: Programming in C++

CS197c: Programming in C++ CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website

More information

Containers in C++ and Java

Containers in C++ and Java Containers in C++ and Java 1 1. Which of the following statements is true? a) Equality on the basis of reference implies equality on the basis of content. b) Equality on the basis of content implies equality

More information

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2 TEMPLATES Today This lecture looks at techniques for generic programming: Generic pointers Templates The standard template library Thebestreferenceis: http://www.cppreference.com/index.html andyoucanalsoconsultchapters6amd7inthetextbook.

More information

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Review from Lecture 8 CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators,

More information

Exceptions, Templates, and the STL

Exceptions, Templates, and the STL Exceptions, Templates, and the STL CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 16 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/

More information

Programming with Haiku

Programming with Haiku Programming with Haiku Lesson 2 Written by DarkWyrm All material 2010 DarkWyrm In our first lesson, we learned about how to generalize type handling using templates and some of the incredibly flexible

More information

Templates and Vectors

Templates and Vectors Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector

More information

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4 Steven J. Zeil July 19, 2013 Contents 1 Overview of Sets and Maps 4 1 2 The Set ADT 6 2.1 The template header................................. 14 2.2 Internal type names.................................

More information

MODULE 33 --THE STL-- ALGORITHM PART I

MODULE 33 --THE STL-- ALGORITHM PART I MODULE 33 --THE STL-- ALGORITHM PART I My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation examples given at the end of this Module.

More information

Associative Containers and Iterators. Ali Malik

Associative Containers and Iterators. Ali Malik Associative Containers and Iterators Ali Malik malikali@stanford.edu Game Plan Recap Associative Containers Iterators Map Iterators The auto keyword (maybe) Range-Based for Loops (maybe) Recap Structs

More information

The Standard Template Library Classes

The Standard Template Library Classes The Standard Template Library Classes Lecture 33 Sections 9.7, 9.8 Robb T. Koether Hampden-Sydney College Wed, Apr 23, 2014 Robb T. Koether (Hampden-Sydney College) The Standard Template Library Classes

More information

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming What the heck is STL???? Another hard to understand and lazy to implement stuff? Standard Template Library The standard template

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 An important part of every container is the type of iterator it supports. This determines which algorithms can be applied to the container. A vector supports random-access iterators i.e., all iterator

More information

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Review from Lecture 7 CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors

More information

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators Review from Lecture 7 Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

1. The term STL stands for?

1. The term STL stands for? 1. The term STL stands for? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d 2. Which of the following statements regarding the

More information

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Standard Template Library. Containers, Iterators, Algorithms. Sequence Containers. Containers

Standard Template Library. Containers, Iterators, Algorithms. Sequence Containers. Containers Standard Template Library The standard template library (STL) contains Containers Algorithms Iterators A container is a way that stored data is organized in memory, for example an array of elements. Algorithms

More information

use static size for this buffer

use static size for this buffer Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation

More information

CPSC 427a: Object-Oriented Programming

CPSC 427a: Object-Oriented Programming CPSC 427a: Object-Oriented Programming Michael J. Fischer Lecture 17 November 1, 2011 CPSC 427a, Lecture 17 1/21 CPSC 427a, Lecture 17 2/21 CPSC 427a, Lecture 17 3/21 A bit of history C++ standardization.

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Unit 4 Basic Collections

Unit 4 Basic Collections Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program

More information

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types Arrays - Vectors Data Types Data Type: I. set of values II. set of operations over those values Example: Integer I. whole numbers, -32768 to 32767 II. +, -, *, /, %, ==,!=, , =,... Which operation

More information

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation Outline EDAF30 Programming in C++ 4. The standard library. Algorithms and containers. Sven Gestegård Robertz Computer Science, LTH 2018 1 Type inference 2 3 The standard library Algorithms Containers Sequences

More information

To use various types of iterators with the STL algorithms ( ). To use Boolean functions to specify criteria for STL algorithms ( 23.8).

To use various types of iterators with the STL algorithms ( ). To use Boolean functions to specify criteria for STL algorithms ( 23.8). CHAPTER 23 STL Algorithms Objectives To use various types of iterators with the STL algorithms ( 23.1 23.20). To discover the four types of STL algorithms: nonmodifying algorithms, modifying algorithms,

More information

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Lecture 10 Class string Exception Handling To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Class template auto_ptr Lec 10 Programming in C++ 1 Class

More information

The Standard Template Library. An introduction

The Standard Template Library. An introduction 1 The Standard Template Library An introduction 2 Standard Template Library (STL) Objective: Reuse common code Common constructs: Generic containers and algorithms STL Part of the C++ Standard Library

More information

Standard Template Library

Standard Template Library Standard Template Library The standard template library (STL) contains CONTAINERS ALGORITHMS ITERATORS A container is a way that stored data is organized in memory, for example an array of elements. Algorithms

More information

2

2 STL Design CSC 330 2 3 4 5 Discussions Associative Containers 6 7 Basic Associative Containers 8 set class 9 map class 10 Example multiset (1) 11 Example multiset (2) 12 Example multiset (3) 13 Example

More information

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation Today CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation Another vector operation: pop back Erasing items from vectors is inefficient! Iterators and iterator operations

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Function Templates. Consider the following function:

Function Templates. Consider the following function: Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But

More information

GridKa School 2013: Effective Analysis C++ Standard Template Library

GridKa School 2013: Effective Analysis C++ Standard Template Library GridKa School 2013: Effective Analysis C++ Standard Template Library Introduction Jörg Meyer, Steinbuch Centre for Computing, Scientific Data Management KIT University of the State of Baden-Wuerttemberg

More information

Overview. Part II: Containers and Algorithms. Overview. Overview

Overview. Part II: Containers and Algorithms. Overview. Overview Part II: Containers and Algorithms Overview Sequential Containers Associative Containers Generic Algorithms C++ is about efficient programming with abstractions. The Standard Library is a good example:

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

STL Quick Reference for CS 241

STL Quick Reference for CS 241 STL Quick Reference for CS 241 Spring 2018 The purpose of this document is to provide basic information on those elements of the C++14 standard library we think are most likely to be needed in CS 241.

More information

Lectures 11,12. Online documentation & links

Lectures 11,12. Online documentation & links Lectures 11,12 1. Quicksort algorithm 2. Mergesort algorithm 3. Big O notation 4. Estimating computational efficiency of binary search, quicksort and mergesort algorithms 5. Basic Data Structures: Arrays

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types. Session 4 - Genericity, Containers Polymorphism Code that works for many types. Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson)

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

C++ 11 and the Standard Library: Containers, Iterators, Algorithms

C++ 11 and the Standard Library: Containers, Iterators, Algorithms and the Standard Library:,, Comp Sci 1575 Outline 1 2 3 4 Outline 1 2 3 4 #i n clude i n t main ( ) { i n t v a l u e 0 = 5 ; // C++ 98 i n t v a l u e 1 ( 5 ) ; // C++ 98 i n t v a

More information

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Review from Lecture 8 CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately, erasing items

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

CS183 Software Design. Textbooks. Grading Criteria. CS183-Su02-Lecture 1 20 May by Eric A. Durant, Ph.D. 1

CS183 Software Design. Textbooks. Grading Criteria. CS183-Su02-Lecture 1 20 May by Eric A. Durant, Ph.D. 1 CS183 Software Design Dr. Eric A. Durant Email: durant@msoe.edu Web: http://people.msoe.edu/~durant/ courses/cs183 (coming soon) Office: CC43 (enter through CC27) Phone: 277-7439 1 Textbooks Required (same

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

15. Pointers, Algorithms, Iterators and Containers II

15. Pointers, Algorithms, Iterators and Containers II 498 Recall: Pointers running over the Array 499 Beispiel 15. Pointers, Algorithms, Iterators and Containers II int a[5] = 3, 4, 6, 1, 2; for (int p = a; p < a+5; ++p) std::cout

More information

Class string and String Stream Processing Pearson Education, Inc. All rights reserved.

Class string and String Stream Processing Pearson Education, Inc. All rights reserved. 1 18 Class string and String Stream Processing 2 18.1 Introduction C++ class template basic_string Provides typical string-manipulation operations Defined in namespace std typedefs For char typedef basic_string

More information

C++: Overview and Features

C++: Overview and Features C++: Overview and Features Richard Newman r.newman@rdg.ac.uk Room CS127 2003-12-11 Programming & Design, 2003 1 Introduction You have: used streams seen how classes are used seen some C++ code Today: good

More information

C++ Standard Template Library

C++ Standard Template Library C++ Standard Template Library CSE 333 Summer 2018 Instructor: Hal Perkins Teaching Assistants: Renshu Gu William Kim Soumya Vasisht C++ s Standard Library C++ s Standard Library consists of four major

More information

To know the relationships among containers, iterators, and algorithms ( 22.2).

To know the relationships among containers, iterators, and algorithms ( 22.2). CHAPTER 22 STL Containers Objectives To know the relationships among containers, iterators, and algorithms ( 22.2). To distinguish sequence containers, associative containers, and container adapters (

More information

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS CSE 100: C++ TEMPLATES AND ITERATORS Announcements iclickers: Please register at ted.ucsd.edu. Start ASAP!! For PA1 (Due next week). 10/6 grading and 10/8 regrading How is Assignment 1 going? A. I haven

More information

Lesson 13 - Vectors Dynamic Data Storage

Lesson 13 - Vectors Dynamic Data Storage Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts

More information

Summary. Design. Layout

Summary. Design. Layout Flat containers wording Document number: P0460R0 Date: 2016-10-15 Reply-to: Sean Middleditch sean@middleditch.us Project: ISO JTC1/SC22/WG21: Programming Language C++ Audience: Library Evolution Working

More information

CS11 Advanced C++ Spring 2018 Lecture 2

CS11 Advanced C++ Spring 2018 Lecture 2 CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are

More information

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic Review from Letctures 3 & 4 C++ class syntax, designing classes, classes vs. structs; Passing comparison functions to

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

Sequential Containers. Ali Malik

Sequential Containers. Ali Malik Sequential Containers Ali Malik malikali@stanford.edu Game Plan Recap Stream wrapup Overview of STL Sequence Containers std::vector std::deque Container Adapters Announcements Recap stringstream Sometimes

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 3 Monday, April 17, 2017 Total - 100 Points B Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 3 Monday, April 17, 2017 Total - 100 Points A Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

Standard Template Library. Outline

Standard Template Library. Outline C++ Standard Template Library Spring 2015 Yanjun Li CS2200 1 Outline Standard Template Library Containers & Iterators STL vector STL list STL stack STL queue Fall 2008 Yanjun Li CS2200 2 Software Engineering

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Document Number: P0429R4 Date: Reply to: 0.1 Revisions... 1

Document Number: P0429R4 Date: Reply to: 0.1 Revisions... 1 Document Number: P0429R4 Date: 2018-05-05 Reply to: Zach Laine whatwasthataddress@gmail.com Audience: LWG A Standard flat_map Contents Contents i 0.1 Revisions.............................................

More information

Prefix Trees Tables in Practice

Prefix Trees Tables in Practice Prefix Trees CS 311 Data Structures and Algorithms Lecture Slides Friday, December 7, 2007 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005

More information

Chapter 17: Linked Lists

Chapter 17: Linked Lists Chapter 17: Linked Lists 17.1 Introduction to the Linked List ADT Introduction to the Linked List ADT Linked list: set of data structures (nodes) that contain references to other data structures list head

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. C++ TEMPLATES http://www.tutorialspoint.com/cplusplus/cpp_templates.htm Copyright tutorialspoint.com Templates are the foundation of generic programming, which involves writing code in a way that is independent

More information

7 TEMPLATES AND STL. 7.1 Function Templates

7 TEMPLATES AND STL. 7.1 Function Templates 7 templates and STL:: Function Templates 7 TEMPLATES AND STL 7.1 Function Templates Support generic programming functions have parameterized types (can have other parameters as well) functions are instantiated

More information

List, Stack, and Queues

List, Stack, and Queues List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of

More information

Standard Containers Library (1)

Standard Containers Library (1) TDDD38 APiC++ Standard Library Containers 211 Standard Containers Library (1) C++ containers are objects that store other objects data structures. controls allocation and deallocation of the stored objects

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we

More information

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS CSE 100: C++ TEMPLATES AND ITERATORS Announcements Gradesource and clickers: We ll be making one more pass for unregistered clickers tonight, but after that you ll be on your own How is Assignment 1 going?

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory C++ 프로그래밍실습 Visual Studio 2015 Templates & STL Contents Exercise Practice1 Templates & STL Practice 1-1 Template Classes #include using namespace std; template class Point { private:

More information

vector<int> second (4,100); // four ints with value 100 vector<int> third (second.begin(),second.end()); // iterating through second

vector<int> second (4,100); // four ints with value 100 vector<int> third (second.begin(),second.end()); // iterating through second C++ Vector Constructors explicit vector ( const Allocator& = Allocator() ); explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); template vector (

More information

More on Templates. Shahram Rahatlou. Corso di Programmazione++

More on Templates. Shahram Rahatlou. Corso di Programmazione++ More on Templates Standard Template Library Shahram Rahatlou http://www.roma1.infn.it/people/rahatlou/programmazione++/ it/ / h tl / i / Corso di Programmazione++ Roma, 19 May 2008 More on Template Inheritance

More information

SETS AND MAPS. Chapter 9

SETS AND MAPS. Chapter 9 SETS AND MAPS Chapter 9 The set Functions Required methods: testing set membership (find) testing for an empty set (empty) determining set size (size) creating an iterator over the set (begin, end) adding

More information

CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic

CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic Announcements: Test 1 Information Test 1 will be held Tuesday, September 18th, 2012 from 2-3:50pm in West Hall Auditorium.

More information

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin Permission is granted to copy and distribute freely, for any purpose, provided the copyright notice above is

More information