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

Save this PDF as:
 WORD  PNG  TXT  JPG

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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++ 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

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

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

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

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

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

vector second (4,100); // four ints with value 100 vector 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

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp 1 EE 355 Unit 10 C++ STL - Vectors and Deques Mark Redekopp 2 Templates We ve built a list to store integers But what if we want a list of double s or char s or other objects We would have to define the

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

CS 103 Unit 12 Slides

CS 103 Unit 12 Slides 1 CS 103 Unit 12 Slides Standard Template Library Vectors & Deques Mark Redekopp 2 Templates We ve built a list to store integers But what if we want a list of double s or char s or other objects We would

More information

EE 355 Unit 11b. Doubly-Linked Lists and Deques. Mark Redekopp

EE 355 Unit 11b. Doubly-Linked Lists and Deques. Mark Redekopp 1 EE 355 Unit 11b Doubly-Linked Lists and Deques Mark Redekopp 2 Singly-Linked List Review Used structures/classes and pointers to make linked data structures Singly-Linked Lists dynamically allocates

More information

Computer Programming C++ (wg) CCOs

Computer Programming C++ (wg) CCOs Computer Programming C++ (wg) CCOs I. The student will analyze the different systems, and languages of the computer. (SM 1.4, 3.1, 3.4, 3.6) II. The student will write, compile, link and run a simple C++

More information

Life cycle of an object construction: creating a new object. Strings: constructors & assignment another type that C and C++ don't provide

Life cycle of an object construction: creating a new object. Strings: constructors & assignment another type that C and C++ don't provide Life cycle of an object construction: creating a new object implicitly, by entering the scope where it is declared explicitly, by calling new construction includes initialization copying: using existing

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

STL Containers, Part I

STL Containers, Part I CS106L Handout #06 Fall 2007 October 10, 2007 STL Containers, Part I Introduction Arguably the most powerful library in the C++ language, the Standard Template Library (STL) is a programmer's dream. It

More information

Vector. Vector Class. class Vector { public: typedef unsigned int size_type;

Vector. Vector Class. class Vector { public: typedef unsigned int size_type; Vector Arrays in C++ must be pre-allocated to accomodate the maximum number of elements. Should an application attempt to add more than this number, the program may abort, or alter storage of adjacent

More information

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 4 (Based on Paul Kube course materials) Lecture 4 Binary search trees Toward a binary search tree implementation using C++ templates Reading: Weiss Ch 4, sections

More information

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

Teaching with the STL

Teaching with the STL Teaching with the STL Joseph Bergin Pace University Michael Berman Rowan College of New Jersey 1 Part 1 Introduction to STL Concepts 2 STL: What and Why Generic data structures (containers) and algorithms

More information

/ binary_search example #include // std::cout #include // std::binary_search, std::sort #include // std::vector

/ binary_search example #include <iostream> // std::cout #include <algorithm> // std::binary_search, std::sort #include <vector> // std::vector Algorithm Searching Example find, search, binary search / binary_search example #include // std::cout #include // std::binary_search, std::sort #include // std::vector bool

More information

Functions and Parameter Passing

Functions and Parameter Passing Chapter 5: Functions and Parameter Passing In this chapter, we examine the difference between function calls in C and C++ and the resulting difference in the way functions are defined in the two languages.

More information

Lectures 19, 20, 21. two valid iterators in [first, last) such that i precedes j, then *j is not less than *i.

Lectures 19, 20, 21. two valid iterators in [first, last) such that i precedes j, then *j is not less than *i. Lectures 19, 20, 21 1. STL library examples of applications Explanations: The member function pop_back removes the last element of the controlled sequence. The member function pop_front removes the first

More information

Major Language Changes, pt. 1

Major Language Changes, pt. 1 C++0x What is C++0x? Updated version of C++ language. Addresses unresolved problems in C++03. Almost completely backwards compatible. Greatly increases expressiveness (and complexity!) of language. Greatly

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Dodatak D Standardna string klasa

Dodatak D Standardna string klasa Dodatak D Standardna klasa from: C++ annotations, by Frank C. Brokken, University of Groningen, ISBN 90 367 0470. The C programming language offers rudimentary support: the ASCII-Z terminated series of

More information

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103

More information

C++ Exception Handling 1

C++ Exception Handling 1 C++ Exception Handling 1 An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such

More information

Cours de C++ Introduction

Cours de C++ Introduction Cours de C++ Introduction Cécile Braunstein cecile.braunstein@lip6.fr Cours de C++ 1 / 20 Généralité Notes Interros cours 1/3 Contrôle TP 1/3 Mini-projet 1/3 Bonus (Note de Participation) jusqu à 2 points

More information

STL Containers, Part II

STL Containers, Part II CS106L Handout #08 Fall 2007 October 17, 2007 STL Containers, Part II Introduction Last week we talked about vector and deque, the STL's two managed array classes. However, the STL offers many other containers,

More information

Chapter 17: Linked Lists

Chapter 17: Linked Lists Chapter 17: Linked Lists Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 17.1 Introduction to the

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

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

CSCI-1200 Data Structures Spring 2017 Lecture 5 Pointers, Arrays, Pointer Arithmetic CSCI-1200 Data Structures Spring 2017 Lecture 5 Pointers, Arrays, Pointer Arithmetic Announcements Submitty iclicker registration is still open. Even if you already registered on the iclicker website,

More information

CSCI 104 C++ STL; Iterators, Maps, Sets. Mark Redekopp David Kempe

CSCI 104 C++ STL; Iterators, Maps, Sets. Mark Redekopp David Kempe CSCI 104 C++ STL; Iterators, Maps, Sets Mark Redekopp David Kempe Container Classes ArrayLists, LinkedList, Deques, etc. are classes used simply for storing (or contain) other items C++ Standard Template

More information

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects Iterators 1 Double Linked and Circular Lists node UML diagram implementing a double linked list the need for a deep copy 2 Iterators on List nested classes for iterator function objects MCS 360 Lecture

More information

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 20 G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not

More information

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is

More information

CS 211 Winter 2004 Sample Final Exam (Solutions)

CS 211 Winter 2004 Sample Final Exam (Solutions) CS 211 Winter 2004 Sample Final Exam (Solutions) Instructor: Brian Dennis, Assistant Professor TAs: Tom Lechner, Rachel Goldsborough, Bin Lin March 16, 2004 Your Name: There are 6 problems on this exam.

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

UEE1302 (1102) F10 Introduction to Computers and Programming (I) Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming (I) Programming Lecture 10 Pointers & Dynamic Arrays (I) Learning Objectives Pointers Data

More information

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 Date: 01/18/2011 (Due date: 01/20/2011) Name and ID (print): CHAPTER 6 USER-DEFINED FUNCTIONS I 1. The C++ function pow has parameters.

More information

Vector and Free Store (Vectors and Arrays)

Vector and Free Store (Vectors and Arrays) DM560 Introduction to Programming in C++ Vector and Free Store (Vectors and Arrays) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne

More information

Standard Template Library STL

Standard Template Library STL Standard Template Library STL What are templates and STL and how to use them? Some common data structures Comparator functions Some more datastructures Iterators Algorithms (sort, find, reverse,...) Other

More information

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. CMPSC11 Final (Study Guide) Fall 11 Prof Hartman Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) This is a collection of statements that performs

More information

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

Splicing Maps and Sets (Revision 1)

Splicing Maps and Sets (Revision 1) Document number: N3645 Date: 2013-05-04 Project: Programming Language C++ Reference: N3485 Reply to: Alan Talbot cpp@alantalbot.com Howard Hinnant howard.hinnant@gmail.com James Dennett jdennett@google.com

More information

Practice Problems CS2620 Advanced Programming, Spring 2003

Practice Problems CS2620 Advanced Programming, Spring 2003 Practice Problems CS2620 Advanced Programming, Spring 2003 April 9, 2003 1. Explain the results of each vector definition: string pals[] = "pooh", "tigger", "piglet", "eeyore", "kanga" a) vector

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a

More information

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 2 Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Arrays and Pointers void myprint(const char *); int main() { char *phrasey = C++Fun ; myprint(phrasey);

More information

Module 9. Templates & STL

Module 9. Templates & STL Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions

More information

Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)

Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) 6.1 Exceptions Exceptions Indicate that something unexpected has occurred or been detected Allow program to deal with the problem

More information

C++ Standard Template Library

C++ Standard Template Library C++ Template Library Comp Sci 1575 Data Structures Outline 1 2 3 4 Data structures Color key: Array sorting algorithms Outline 1 2 3 4 is part of standard namespace Old diagram of the standard Outline

More information

Pairing off iterators

Pairing off iterators Pairing off iterators Anthony Williams 8th May 2002 1 Introduction Recently, a colleague approached me with an interesting problem; he had two containers with corresponding elements, so the n-th entry

More information

Part 3: Function Pointers, Linked Lists and nd Arrays

Part 3: Function Pointers, Linked Lists and nd Arrays Part 3: Function Pointers, Linked Lists and nd Arrays Prof. Dr. Ulrik Schroeder C++ - Einführung ins Programmieren WS 03/04 http://learntech.rwth-aachen.de/lehre/ws04/c++/folien/index.html Pointer to functions

More information

Lecture 2 Tao Wang 1

Lecture 2 Tao Wang 1 Lecture 2 Tao Wang 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common programming errors

More information

Chapter 17 vector and Free Store

Chapter 17 vector and Free Store Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

Supplement I.A: Glossary. For Introduction to C++ Programming, Second Edition By Y. Daniel Liang

Supplement I.A: Glossary. For Introduction to C++ Programming, Second Edition By Y. Daniel Liang Chapter 1 Supplement I.A: Glossary For Introduction to C++ Programming, Second Edition By Y. Daniel Liang assembly language A low-level programming language in which a mnemonic is used to represent each

More information

C++ Undefined Behavior What is it, and why should I care?

C++ Undefined Behavior What is it, and why should I care? C++ Undefined Behavior What is it, and why should I care? Marshall Clow Qualcomm marshall@idio.com http://cplusplusmusings.wordpress.com (intermittent) Twitter: @mclow ACCU 2014 April 2014 What is Undefined

More information

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup www.stroustrup.com/programming Abstract arrays, pointers, copy semantics, elements access, references Next lecture: parameterization

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

TEMPLATES AND ITERATORS

TEMPLATES AND ITERATORS TEMPLATES AND ITERATORS Problem Solving with Computers-I https://ucsb-cs24-sp17.github.io/ 2 Announcements Checkpoint deadline for pa04 (aka lab05) is due today at 11:59pm Be sure to push your code to

More information

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words. , ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter

More information

C++ How To Program 10 th Edition. Table of Contents

C++ How To Program 10 th Edition. Table of Contents C++ How To Program 10 th Edition Table of Contents Preface xxiii Before You Begin xxxix 1 Introduction to Computers and C++ 1 1.1 Introduction 1.2 Computers and the Internet in Industry and Research 1.3

More information

The Standard C++ Library

The Standard C++ Library The Standard C++ Library Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface Q: What types can we put in a template param? A: Type which models the requested concept. Concepts - Example

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance

More information

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT... Steven J. Zeil July 11, 2013 Contents 1 Definition: Binary Search Trees 2 1.1 The Binary Search Tree ADT.................................................... 3 2 Implementing Binary Search Trees 7 2.1 Searching

More information

The Standard Template Library

The Standard Template Library The Standard Template Library 1 Components Sequential Access Containers Vector Container Vector Constructors Vector Example Vector Indexing Iterators Vector Iterator Example Iterator Operations Insertion

More information

Software Development with C++ Templates

Software Development with C++ Templates Software Development with C++ Templates Lab Submission 1 Exercises should be solved in groups of two. However, with approval from the lecturer, exercises may also be solved alone or in groups of three.

More information

PIC 10A. Lecture 23: Intro to STL containers

PIC 10A. Lecture 23: Intro to STL containers PIC 10A Lecture 23: Intro to STL containers STL STL stands for Standard Template Library There are many data structures that share similar features These data structures can be manipulated by a common

More information

4.1 Ordered Lists Revisited

4.1 Ordered Lists Revisited Chapter 4 Linked-lists 4.1 Ordered Lists Revisited Let us revisit our ordered-list. Let us assume that we use it for storing roll numbers of students in a class in ascending order. We can make the assumption

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information