A quote, and footnote, from The Design and Evolution of C++, by Bjarne Stroustrup (1995):

Size: px
Start display at page:

Download "A quote, and footnote, from The Design and Evolution of C++, by Bjarne Stroustrup (1995):"

Transcription

1 The Standard Library A quote, and footnote, from The Design and Evolution of C++, by Bjarne Stroustrup (1995): I would like to see list and associative array (map) templates in the standard library. However, as of Release 1.0 these classes may be lost due to the urgency of completing the core language in a timely fashion. 1 1 Here I have the great pleasure of eating my words! The committee did rise to the occasion and approved a splendid library of containers, iterators, and fundamental algorithms designed by Alex Stepanov. This library, often called the STL, is an elegant, efficient, formally sound, and well-tested framework for containers and their use. The addition of templates to C++ facilitated the development of containers that could support any data type, and do so efficiently. This greatly enhances the power of C++, placing it in a class by itself. This document describes some of the features of the standard library container classes. For a more thorough discussion and up-to-date releases of the STL, consult the following references: The C++ Programming Programming Language, by Bjarne Stroustrup The definitive reference for C++, extensive coverage of the STL is included. The C++ Standard Library, by Nicolai M. Josuttis An excellent tutorial/reference for the STL that's easy to read and understand. Silicon Graphics version of the STL, adopted by Microsoft for Visual C++ is available at this web site. You'll also extensive guides and tutorials for the STL. Ports of the STL to several environments are available at this web site. Container classes contain a collection of elements and support operations such as insert and erase to add or delete objects from the container. The elements may stored in an array, a linked list, or a binary tree. Elements are accessed with iterators. An iterator can be thought of as a pointer to the element being accessed. In some cases this is the actual implementation. Operations, such as pre and post-increment, can be used with iterators to index to the next element. For example: list<int> c; list<int>::const_iterator i;... for (i = c.begin(); i!= c.end(); ++i) cout << *i << endl; This illustrates a list container that stores elements in a linked list. Collection c is defined to contain integers. All containers have iterator and const_iterator types. Use const_iterator if code does not modify the referenced object. All containers also have begin and end member functions. The begin function returns an iterator designating the first element in the container, and the end function returns an iterator designating one past the last element. Dereference the iterator to access an element referenced by an iterator. If the container holds structures, use the structure dereferencing operator (i->value). The same code, using a vector (array) follows:

2 vector<int> c; vector<int>::const_iterator i;... for (i = c.begin(); i!= c.end(); ++i) cout << *i << endl; To facilitate changes and simplify coding it is often convenient to define a type for the collection. typedef list<int> Data; Data c; Data::const_iterator i;... for (i = c.begin(); i!= c.end(); ++i) cout << *i << endl; Iterators for each class are implemented in a similar manner, so it is easy to switch between different containers. Iterators can be used with algorithms to perform a task. For example, the following code will sort the contents of a container: sort(c.begin(), c.end()); Iterator ranges, such as the range specified in the sort algorithm, supply an open range [beg,end). This notation indicates that the first element, beg, is included in the range, and the last element, end, is not included in the range. Since c.end() in this example references one past the last element, the entire container is sorted. If the end of a range were to be included the last element, this would cause problems in the iterator implementation. Consider the following: for (i = c.begin(); i <= c.end(); ++i) cout << *i << endl; This code would be correct if c.end() referenced the last element in a range. However, support is required for the less-than-or-equal-to operator for this iterator. It's easily done if the underlying implementation is an array. For linked lists and trees this is problematic since addresses associated with a node in a list or tree do not imply any ordering. Notice the use of the pre-increment operator. Although a post-increment operator would also work, it is less efficient. For an operation such as ++i the iterator increments to the next element, then returns the iterator. If instead we specify i++ the iterator must save its state, increment to the next element, then return the saved state. This extra step can easily be avoided by using the preincrement form of the operator. The overriding priority in library design is efficient execution. In every case where there was a choice between safety and efficiency, efficiency was preferred. For example, the pop_back function in the vector class that deletes the last element in a vector assumes that there is a valid element to delete. If the vector is empty, and this function is called, results are undetermined. For a safer container, write a wrapper that performs the desired checking. The standard library is in the std namespace. To simplify presentation, the scope resolution for this namespace has been omitted in this paper.

3 Useful Tools Pair The pair struct, defined in the <utility> header, combines two values in one structure. This facilitates passing and returning two arguments at once. Since it s a struct we can access the data members directly. This is best illustrated by example. Example 1 pair<int, double> x(5, 2.5); Pair x is initialized with values 5 and 2.5. Example 2 pair<int, double> x; x.first = 5; x.second = 2.5; Pair x is initialized with values 5 and 2.5. Example 3 pair<double, double> circarea(double radius) { pair<double, double> x; x.first = 2 * 3.14 * radius; x.second = 3.14 * radius * radius; return x; pair<double, double> p = circarea(10.0); cout << "circumference = " << p.first << ", area = " << p.second << endl; The function circarea computes the circumference and area of a circle, and returns both values as a pair. Example 4 double distance(const pair<double, double>& p) { return sqrt(p.first * p.first + p.second * p.second); cout << distance(make_pair(3.0, 4.0)) << endl; Convenience function make_pair is invoked to create a pair that is passed to the distance function. Min/Max The min and max functions, provided in the <algorithm> header, compare values and return the minimum or maximum value respectively. Both values must be of the same type. template <class T> inline const T& min (const T& a, const T& b) { return b < a? b : a; template <class T> inline const T& max (const T& a, const T& b) { return a < b? b : a;

4 Swap The swap function, provided in the <algorithm> header, swaps two values of the same type. template <class T> inline void swap(t& a, T& b) { T tmp(a); a = b; b = tmp; Containers Overview Containers can be classified as sequential or associative. Sequential containers consist of an ordered collection where the position of each element depends on the order of insertion. of sequential containers include vector, deque (rhymes with check), and list. Associative containers are sorted collections where the position of each element depends on its value. of associative containers include set, multiset, map, and multimap. Common Operations All container classes support the following operations. Initialize T c T c1(c2) T c(beg,end) empty container c1 = copy of c2 create c with copies of [beg,end) c.~t() delete all elements c.size() number of elements in container c.empty() true if container is empty (faster than size == 0) Compare c1 == c2 comparison operator == c1!= c2 comparison operator!= c1 < c2 comparison operator < c1 > c2 comparison operator > c1 <= c2 comparison operator <= c1 >= c2 comparison operator >= Assign/Swap c1 = c2 c1.swap(c2) swap(c1,c2) assignment operator swap data between c1, c2: O(1) swap data between c1, c2: O(1) Iterators c.begin() returns iterator &c[first] c.end() returns iterator &c[last + 1] c.rbegin() returns reverse iterator &c[last] c.rend() returns reverse iterator &c[first 1]

5 Vector The vector container is typically implemented as a dynamic array that can grow in one direction. The following operations are supported: size and capacity c.capacity() c.reserve(n) random access c[index] c.at(index) push/pop c.front() c.back() c.push_back(elem) c.pop_back() insert/erase c.insert(pos,elem) c.insert(pos,n,elem) c.insert(pos,beg,end) c.erase(pos) c.erase(beg,end) c.clear() c.resize(n) c.resize(n,elem) returns max number of elements w/o reallocation increases capacity to n elements references c[index] references c[index] with range checking returns first element returns last element append elem at end delete last element insert elem at position pos insert n copies of elem at position pos insert elements [beg,end) at position pos delete elem at pos, return pointer to successor delete elems [beg,end), return pointer to successor delete all elements increase size to n elements using default constructor increase size to n elements with elem as a value Push/pop operations at the end of the vector take constant time unless the array must be extended. If there is insufficient contiguous space to extend the array, then another array is allocated, the elements are copied to the new array, and the old array is deleted. To preclude this possibility, use reserve to pre-allocate sufficient space. There are no push_front or pop_front operations, as they would be very inefficient. Insert/erase operations at random locations execute in linear time. Subscripts can be used for direct access to vector elements. However, the element must already exist prior to access. That is, subscripts should be in the range 0.. (c.size() 1). #include <vector> typedef vector<int> Collection; Collection c; // append c.push_back(5); c.push_back(6); c.push_back(7); c[1] = c[0] + c[2]; cout << c.front() << endl; // output: 5 cout << c.back() << endl; // output: 7 c.pop_back(); cout << c.back() << endl; // output: 12 // iterator, output: 5 12 Collection::const_iterator i; for (i = c.begin(); i!= c.end(); ++i) cout << *i << " ";

6 // direct access, output: 5 12 Collection::size_type size = c.size(); Collection::size_type j; for (j = 0; j < size; ++j) cout << c[j] << " "; Deque A deque (rhymes with check) is a double-ended queue that can grow in both directions. The interface is the same as the vector class, except there are no capacity and reserve functions, and deques include the following push/pop operations: push/pop c.front() c.push_front(elem) c.pop_front() c.back() c.push_back(elem) c.pop_back() returns first element insert elem at beginning delete first element returns last element append elem at end delete last element Deques are often implemented as a set of arrays. Initially one array is allocated, and the first push places an element at the middle of the array. Subsequent pushes can add elements in both directions. When the array bounds is encountered, an additional array is allocated. Push/pop operations at both ends of the deque take constant time. Insert/erase operations at random locations execute in linear time. Direct access is provided, but is not as fast as direct access with the vectors since an extra level of indirection is required to determine which array holds the element. #include <deque> typedef deque<int> Collection; Collection c; // push c.push_back(6); c.push_back(7); c.push_front(5); c.push_front(4); c[1] = c[0] + c[2]; c.pop_front(); cout << c.front() << endl; // output: 10 c.pop_back(); cout << c.back() << endl; // output: 6

7 // iterator, output: 10 6 Collection::const_iterator i; for (i = c.begin(); i!= c.end(); ++i) cout << *i << " "; // direct access, output: 10 6 Collection::size_type size = c.size(); Collection::size_type j; for (j = 0; j < size; ++j) cout << c[j] << " "; List A list is implemented as a doubly linked list. The following operations are supported: push/pop c.front() c.push_front(elem) c.pop_front() c.back() c.push_back(elem) c.pop_back() insert/erase c.insert(pos,elem) c.insert(pos,n,elem) c.insert(pos,beg,end) c.erase(pos) c.erase(beg,end) c.clear() c.remove(val) c.remove_if(op) c.resize(num) c.resize(num,elem) returns first element insert elem at beginning delete first element returns last element append elem at end delete last element insert elem at position pos (returns pos of new element) insert n copies of elem at pos (returns nothing) insert at pos elements [beg,end) (returns nothing) delete elem at pos, return pointer to successor delete elems [beg,end), return pointer to successor delete all elements delete all elements with value val delete all elements for which op(elem) is true increase size to num elements using default constructor increase size to num elements initial with elem sort/merge c.sort() sort, comparing with operator < c.sort(op) sort, comparing with function op(e1,e2) c1.merge(c2) move c2 to c1, merging sorted lists c.reverse() reverse order of elements c.unique() remove duplicates of consecutive elements c.unique(op) remove duplicates for which op(e1,e2) is true Push/pop operations at both ends of the list take constant time. Insert/erase operations at random locations take constant time since only pointer adjustments are needed. The list class does not support direct access, so the sort algorithm may not be utilized. For this reason a sort member function is included with the list class that does a stable sort in O(n lg n) time on average. Typically a merge sort is done, manipulating the list with splice operations. See Josuttis for a description of splice operations. #include <list> typedef list<int> Collection; Collection c; // push c.push_back(6); c.push_back(7); c.push_front(5);

8 c.push_front(4); c.pop_front(); cout << c.front() << endl; // output: 5 c.pop_back(); cout << c.back() << endl; // output: 6 // iterator, output: 5 6 Collection::const_iterator i; for (i = c.begin(); i!= c.end(); ++i) cout << *i << " "; // reverse order of elements c.reverse(); // sort elements c.sort(); Set/MultiSet Sets and multisets are ordered collection of keys the position of each key in the set is determined by its value. Keys must be unique in sets, but duplicate keys are allowed in multisets. Sets and multisets are typically implemented as a balanced binary tree. The following operations are supported: insert functions, sets insert(elem) insert(pos,elem) returns pair<iterator,bool> (see below) inserts elem and returns iterator to inserted element insert functions, multisets insert(elem) inserts elem and returns iterator to inserted element insert(pos, elem) inserts elem and returns iterator to inserted element erase c.erase(elem) c.erase(pos) c.erase(beg,end) c.clear() search count(elem) find(elem) lower_bound(elem) upper_bound(elem) equal_range(elem) delete all elements with value elem delete element at position pos delete elements on range [beg,end) delete all elements returns number of elements with value elem returns position of first element with value elem returns position of first element >= elem returns position of first element > elem returns pair<lower_bound,upper_bound> No push/pop operations are allowed on sets, as the position of an element is determined by its value. Insert operations may provide a position, but this is taken as a hint to improve insertion time. Insert/erase operations at random locations take O(lg n) time. The insert operation for sets returns a pair. The first member of the pair returns the position of the newly inserted element, and the second member of the pair indicates whether or not the operation was successful. Insertion can fail in sets if an attempt is made to insert duplicate keys. Erase operations for vector, deque, and list return a pointer to the successor element. This is not done in sets or multisets as the operation would be too expensive.

9 By default, elements are stored in increasing order using the < operator. The template definition for sets and multisets includes a Compare parameter: template <class T, class Compare = less<t>,...> Where less<t> is defined as template<class T> struct less { bool operator() (const T& x, const T& y) const { return x < y; ; Override the 2 nd parameter for a different sort order. e.g., set<int,greater<int> > s; will store integer elements in decreasing order. An extra space is required between each > so it won t be parsed as the binary shift operator >>. #include <set> typedef set<int> Collection; Collection c; c.insert(6); c.insert(7); c.insert(5); c.insert(4); // attempt to insert a duplicate key pair<collection::iterator,bool> status; status = c.insert(5); if (status.second) cout << "Success!" << endl; // output collection in increasing order Collection::const_iterator i; for (i = c.begin(); i!= c.end(); ++i) cout << *i << " "; // delete entries 5, 6, 7 Collection::iterator pos1, pos2; pos1 = c.find(5); pos2 = c.find(7); c.erase(pos1,++pos2); Map/MultiMap Maps and multimaps are ordered collections of key/value pairs the position of each pair in the map is determined by its key. The keys must be unique in maps, but duplicate keys are allowed in multimaps. Maps and multimaps are typically implemented as a balanced binary tree. Insert/erase operations at random locations take O(lg n) time. Maps are similar to sets, only iterators reference key/value pairs. You can change the value, but not the key, using iterators. To change a key, first erase the old record, then insert a new one with the revised key. By default, elements are stored in increasing order using the < operator. The template definition for maps and multimaps is as follows:

10 template <class Key, class T, class Compare = less<key>,...> Override the 3 rd parameter for a different sort order. The following illustrates a thesaurus implemented as a multimap. #include <map> #include <string> typedef multimap<string,string> Collection; Collection c; c.insert(make_pair("big", "large")); c.insert(make_pair("big", "huge")); c.insert(make_pair("enormous", "huge")); // alter the value of a key/value pair Collection::iterator pos = c.find("enormous"); if (pos!= c.end()) pos->second = "megalithic"; // print all values for key "big" string t("big"); for (pos = c.lower_bound(t); pos!= c.upper_bound(t); ++pos) cout << pos->second << endl; // print all keys for value "huge" string u("huge"); for (pos = c.begin(); pos!= c.end(); ++pos) if (pos->second == u) cout << pos->first << endl; // delete all elements with value "huge" string v("huge"); pos = c.begin(); while (pos!= c.end()) { if (pos->second == v) c.erase(pos++); else ++pos; Container Adapters // is this okay? Stack A stack supports a last-in-first-out (LIFO) queue and is based on the deque class. Push/pop operations are done in constant time. The following operations are supported: push/pop c.push(elem) c.top() c.pop() size c.size() c.empty() inserts an element into the stack returns the top of stack deletes the top of stack (no return value) returns number of elements in stack returns true if stack is empty

11 #include <stack> stack<int> s; s.push(1); s.push(2); s.push(3); cout << s.top() << endl; // 3 s.pop(); cout << s.top() << endl; // 2 s.pop(); cout << s.top() << endl; // 1 s.pop(); s.push(10); s.push(20); s.push(30); // output and pop all elements while (!s.empty()) { cout << s.top() << endl; s.pop(); Queue A queue supports a first-in-first-out (FIFO) queue and is based on the deque class. Push/pop operations are done in constant time. The following operations are supported: push/pop c.push(elem) c.front() c.back() c.pop() size c.size() c.empty() #include <queue> queue<int> q; q.push(1); q.push(2); q.push(3); cout << q.front() << endl; // 1 cout << q.back() << endl; // 3 q.pop(); cout << q.front() << endl; // 2 q.pop(); cout << q.front() << endl; // 3 q.pop(); inserts an element on back of the queue returns the element at the front of the queue returns the element at the back of the queue deletes element from front of the queue returns number of elements in queue returns true if queue is empty Priority Queue A priority queue returns elements in an ordered sequence. Priority queues are usually implemented as heaps and based on the vector class. Push/pop operations take O(lg n) time. The following operations are supported:

12 push/pop c.push(elem) c.top() c.pop() size c.size() c.empty() inserts an element into the priority queue returns the next element in the priority queue deletes an element from the priority queue returns number of elements in priority queue returns true if priority queue is empty By default the largest element is returned first. To change the order, modify the 3 rd template parameter: priority_queue<class T, vector<t>, class Compare = less<key> > The default uses the vector class as a basis, and invokes the less function object. Changing less to greater will reverse the order causing the priority queue to return the smallest element first. #include <queue> priority_queue<int> pq; pq.push(2); pq.push(1); pq.push(3); cout << pq.top() << endl; // 3 pq.pop(); cout << pq.top() << endl; // 2 pq.pop(); cout << pq.top() << endl; // 1 pq.pop(); Iterator Adapters Iterator adapters allow algorithms to operate in reverse, utilize insert mode, and access I/O streams. Random Access Iterators Iterators associated with the vector and deque containers are random access and can participate in arithmetic expressions including iter + n iter n iter += n iter1 < iter2 iter1 <= iter2 n + iter n iter iter -= n iter1 > iter2 iter1 >= iter2 You can also take the distance between two iterators. iter1 iter2 This returns the distance, or the number of container objects, between the two iterators. Similar operations are possible with non random-access containers, such as the list container, with the following functions. advance(pos, n) distance(pos1, pos2) // advance iterator by n objects // distance in objects between two iterators In this case the iterator is incremented (++ operator) to achieve the desired result.

13 Reverse Iterators The following functions support indexing through a collection in a reverse direction: c.rbegin() c.rend() returns position of last element returns position before first element Reverse iterators (reverse_iterator) change the sense of the increment/decrement operators, so increment the iterator to index in reverse. // print collection, from last to first element vector<int>::reverse_iterator i; for (i = c.rbegin(); i!= c.rend(); ++i) cout << *i << endl; Insert Iterators Use insert iterators to insert elements where a copy is normally done. The following iterators are supported: iterator calls back_inserter push_back front_inserter push_front inserter insert // establish collections // c = 1 2 c.push_back(1); c.push_back(2); // d = d.push_back(10); d.push_back(20); d.push_back(30); // e = e.push_back(10); e.push_back(20); e.push_back(30); copy (c.begin(), c.end(), d.begin()); // d = copy (c.begin(), c.end(), back_inserter(e)); // e =

14 Stream Iterators Iterators are provided that interface with I/O streams. By convention an istream argument is used for the istream_iterator for the beginning of the stream, and no arguments are used to designate the end. vector<string> c; // input strings and place them in vector "c". Stop at EOF or error. copy( istream_iterator<string>(cin), // begin() istream_iterator<string>(), // end() back_inserter(c)); // output contents of vector "c", with a newline between each element copy(c.begin(), c.end(), ostream_iterator<string>(cout, "\n"));

15 Algorithms Use algorithms to manipulate objects in containers. Most algorithms require include files <algorithm> and <functional>. The following program illustrates the use of algorithms applied to the vector container. In subsequent sections we will examine algorithms in detail. #include <string> #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Employee { int empno; // employee number string name; // employee name double pay; // salary ; typedef vector<employee> Collection; bool cmpname(const Employee& e1, const Employee& e2) { return e1.name < e2.name; void output(const Employee& e) { cout << e.empno << " " << e.name << " " << e.pay << endl; class empnoequals { public: empnoequals(int empno_) : empno(empno_) { bool operator()(const Employee& e) const { return e.empno == empno; private: int empno; ; int main() { Collection emp; Employee t; // new employee t.empno = 1001; t.name = "John"; t.pay = 1000; emp.push_back(t); // assume several others have been added... // sort employees in ascending order by name sort(emp.begin(), emp.end(), cmpname); // output sorted employees for_each(emp.begin(), emp.end(), output); // find employee with empno == 1001 Collection::iterator i; i = find_if(emp.begin(), emp.end(), empnoequals(1001)); // add $10 to employee 1001's pay if (i!= emp.end()) i->pay += 10; return 0;

16 Classification Algorithms may be classified in the following categories: nonmodifying. Algorithms, such as count and find, will not change the order or value of elements in a collection. modifying. Algorithms, such as copy and replace, may change the order or value of elements in a collection. removing. Remove specified elements. mutating. Change the order of elements in a collection. sorting. Order elements in a collection based on values. sorted range. Algorithms, such as binary search, work on a sorted range of elements. numeric. Mathematical algorithms to compute sums and products. Several algorithms have a suffix that implies their function: _if suffix. A function or function object is implied. For example: find find value find_if find value that satisfies criteria of function _copy suffix. A copy of the elements is placed in another collection. reverse reverse order reverse_copy copy reversed elements to another collection Before investigating algorithms for each category, we'll examine the for_each algorithm. This algorithm may be classified as both nonmodifying and modifying. for_each The for_each algorithm iterates through the elements of a range, calling a function for each element. The algorithm is similar to the following: template<class T, class F) F for_each(t pos, T last, F op) { while (pos!= last) op(*pos++); return op; When iteration is complete, the last value of op is returned. Although the implementation for many of the algorithms is relatively short, they provide power and flexibility to the container classes. void print(int x) { cout << x << endl; void timestwo(int& x) { x = x + x; vector<int> c; // print each element for_each(c.begin(), c.end(), print); // multiply each element by two for_each(c.begin(), c.end(), timestwo);

17 Nonmodifying Nonmodifying algorithms do not change the value or position of elements in a collection. Count and find are implemented as member functions in the list class. // unary predicate bool even(int x) { return x % 2 == 0; vector<int> c; // count the number of 4's n = count(c.begin(), c.end(), 4); // count the number of even numbers n = count_if(c.begin(), c.end(), even); // find the first occurrence of the number 4 pos = find(c.begin(), c.end(), 4); // find the first occurrence of an even number pos = find_if(c.begin(), c.end(), even); // find the location of the smallest element pos = min_element(c.begin(), c.end()); // find the location of the largest element pos = max_element(c.begin(), c.end()); // binary predicate bool compareaverage(const Employee& s1, const Employee& s2) { return s1.pay < s2.pay; struct Employee { string name; double pay; ; vector<employee> c; // find student with highest pay pos = max_element(c.begin(), c.end(), compareaverage); Modifying Modifying algorithms change the contents of a collection. void timestwo(int& x) { x = x + x; // predicate function bool even(int x) { return x % 2 == 0; // copy c1 to c2 (c2 must have sufficient room) copy(c1.begin(), c1.end(), c2.begin());

18 // append c1 to the end of c2 copy(c1.begin(), c1.end(), back_inserter(c2)); // transform values in c1 (times two), and place the results in c2 transform(c1.begin(), c1.end(), c2.begin(), timestwo); // replace all instances of 4 with 8 replace(c.begin(), c.end(), 4, 8); // replace all even numbers with 0 replace_if(c.begin(), c.end(), even, 0); Removing The remove algorithm shifts elements from the end of a collection to replace removed entries. Collection size does not change, and the position of the new end-of-collection is returned. A subsequent call to erase will delete excess entries. For the list class, use the remove member function. // predicate function bool even(int x) { return x % 2 == 0; // remove all elements with value 5 to the end of the collection // state: pos = remove(c.begin(), c.end(), 5); // state: c.erase(pos, c.end()); // state: // remove all even elements to the end of the collection // state: pos = remove_if(c.begin(), c.end(), even); // state: c.erase(pos, c.end()); // state: // operations may be combined as follows: c.erase(remove_if(c.begin(), c.end(), even), c.end()); // copy all elements not equal to value 3 remove_copy(c1.begin(), c1.end(), back_inserter(c2), 3); // copy all odd numbers (predicate fails) remove_copy_if(c1.begin(), c1.end(), back_inserter(c2), even); // remove duplicates to the end of the collection pos = unique(c.begin(), c.end()); c.erase(pos, c.end()); // copy c1 to c2, eliminating any duplicates unique_copy(c1.begin(), c1.end(), back_inserter(c2)); Mutating Mutating algorithms change the order of elements in a collection. // reverse order of elements reverse(c.begin(), c.end());

19 // print elements in reverse order (collection not changed) reverse_copy(c.begin(), c.end(), ostream_iterator<int>(cout,"\n")); // rotate elements, using "begin+1" as the new first element // state: rotate(c.begin(), c.begin() + 1, c.end()); // state: // print rotated elements (collection not changed) rotate_copy(c.begin(), c.begin() + 1, ostream_iterator<int>(cout,"\n")); Sorting Sorting algorithms run in O(n lg n) time on average. Stable sorts, where the order of identical keys is not changed, runs in O(n lg n) time if there is sufficient memory, or O(n lg n * lg n) time otherwise. Use sort algorithms on containers that support random access such as vector and deque. The list class has its own sort member function. Associative containers, such as set and map, place elements in order on insertion. // binary predicate bool compare(int x, int y) { return x > y; // sort elements in collection in increasing order (operator "<") sort(c.begin(), c.end()); // sort elements in collection in decreasing order sort(c.begin(), c.end(), compare); // another way to sort elements in collection in decreasing order sort(c.begin(), c.end(), greater<int>()); // stable sort, increasing order stable_sort(c.begin(), c.end()); // stable sort, decreasing order stable_sort(c.begin(), c.end(), compare); // stable sort, decreasing order stable_sort(c.begin(), c.end(), greater<int>()); Sorted Range These algorithms assume the elements in the range specified are ordered according to a sort criteria. They may be used on containers that do not have random access, such as the list container. In this case, timing is linear as each element must be examined. Timing is logarithmic for random access containers. Algorithms lower_bound, upper_bound, and equal_range are also implemented as member functions for the associative containers. // binary predicate bool compare(int x, int y) { return x < y;

20 // Just need to know if it's there? Then do a binary_search. // Otherwise, do lower_bound, upper_bound, or equal_range. bool found = binary_search(c.begin(), c.end(), 5); bool found = binary_search(c.begin(), c.end(), 5, compare); // lower_bound returns the position of the first element >= value pos = lower_bound(c.begin(), c.end(), 5); pos = lower_bound(c.begin(), c.end(), 5, compare); // upper_bound returns the position of the first element > value pos = upper_bound(c.begin(), c.end(), 5); pos = upper_bound(c.begin(), c.end(), 5, compare); // pair.first is lower_bound // pair.second is upper_bound pair<iter,iter> p = equal_range(c.begin(), c.end(), 5); pair<iter,iter> p = equal_range(c.begin(), c.end(), 5, compare); // check whether several elements are present // returns true if c1 contains all elements listed in c2 // both c1 and c2 must be ordered bool found = includes(c1.begin(), c1.end(), c2.begin(), c2.end()); bool found = includes(c1.begin(), c1.end(), c2.begin(), c2.end(), compare); // merge ordered collections c1, c2 ==> c3 (all) // ( ), ( ) ==> ( ) merge(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3)); merge(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3), compare); // union of ordered collections c1, c2 ==> c3 // select elements in either 1 st or 2 nd collections // ( ), ( ) ==> ( ) set_union(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3)); set_union(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3), compare); // intersection of ordered collections c1, c2 ==> c3 // select elements in both 1 st and 2 nd collections // ( ), ( ) ==> ( ) set_intersection(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3)); set_union(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3), compare); // difference of ordered collections c1, c2 ==> c3 // select elements in 1 st but not in 2 nd collection // ( ), ( ) ==> ( ) set_difference(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3)); set_difference(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3), compare); // symmetric difference of ordered collections c1, c2 ==> c3 // select elements in 1 st or 2 nd but not both collections // ( ), ( ) ==> ( ) set_symmetric_difference(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3)); set_symmetric_difference(c1.begin(), c1.end(), c2.begin(), c2.end(), back_inserter(c3), compare);

21 Numeric Numeric algorithms facilitate the computation of values on collections. // add elements in collection (initialize total to 0) double sum = accumulate(c.begin(), c.end(), 0); // multiply elements in a collection (initialize total to 1, op == multiply) double product = accumulate(c.begin(), c.end(), 1, multiplies<double>()); // compute dot product of c1 and c2 double dotproduct = inner_product(c1.begin(), c1.end(), c2.begin(), 0); Function Objects Function objects, or functors, are classes that act like functions. Unlike simple functions, it is possible to store state information in a function object. In addition, a function object is a type, and this is required under some circumstances. Modify Elements Use for_each to modify elements in a collection. Example 1 adds 10 to each element in the collection. A more general solution is shown in Example 2. When for_each executes, the Add constructor is called to create a temporary object with 10 stored in value. Later, the for_each algorithm will call Add for each element, passing the element as a parameter. This will invoke operator(), passing the element, and 10 will be added to the element. As this example illustrates, function objects have state (the value 10 in this case). Example 1 void add10(int &x) { x += 10; // add 10 to each element for_each(c.begin(), c.end(), add10); Example 2 class Add { public: Add(int v) : value(v) { void operator() (int& x) const { x += value; private: int value; ; // add 10 to each element for_each(c.begin(), c.end(), Add(10)); // add 20 to each element for_each(c.begin(), c.end(), Add(20));

22 Search for Value Use find or find_if to search for an element in a collection. Use function objects to save the search value and construct the predicate for collections containing structures. Example struct Employee { string name; double pay; ; class nameequals { public: nameequals(const string& name_) : name(name_) { bool operator()(const Employee& x) const { return x.name == name; private: string name; ; pos = find_if(x.begin(), x.end(), nameequals("adams")); Ordering Criteria If you're using a primitive data type, ordering criteria can be specified using one of the built-in function object predicates such as less or greater. For more complex criteria, create your own function object as shown in the following example. Note that a simple function would not compile correctly, as the set class expects ordering criteria to be a type. Example struct Employee { string name; double pay; ; class EmployeeOrder { public: bool operator() (const Employee& s1, const Employee& s2) const { return s1.pay < s2.pay; ; typedef set<employee, EmployeeOrder> EmployeeData; EmployeeData data; Employee s; s.name = "Joe"; s.pay = 95; data.insert(s);

23 Average Value The following example iterates through a collection and outputs the numeric average. Recall that for_each returns the last value of the procedure operator. In this case it returns the last state of the Average class that contains the number and sum of the elements. Example class Average { public: // called initially to create temporary Average() : num(0), sum(0) { // called for each element void operator() (int x) { num++; sum += x; // implicit type conversion, Average to double operator double() const { return static_cast<double>(sum) / static_cast<double>(num); private: int num; // number of elements int sum; // sum of elements ; double avg = for_each(c.begin(), c.end(), Average()); cout << "average = " << avg << endl; Although this looks a bit mysterious, recall that for_each returns the functor after iteration. Since we've included a conversion to double, this code executes and the average is calculated. template<class T, class F) F for_each(t pos, T last, F op) { while (pos!= last) op(*pos++); return op; Future Work The following container classes are not part of the ANSI standard, but are supported by SGI and will probably be included in the standard library in the future: slist. A container based on a singly-linked list. hash_set, hash_multiset, hash_map, hash_multimap. Containers that utilize a hash function to access data. Specify your own hash function, and an equality function that determines whether keys are equal.

CS302. Today s Topics: More on constructor/destructor functions More on STL <list>

CS302. Today s Topics: More on constructor/destructor functions More on STL <list> CS302 Today s Topics: More on constructor/destructor functions More on STL Tuesday, Sept. 5, 2006 Recall: Constructor and destructor functions What are they? Remember example: Constructor function

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

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

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

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

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

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

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

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

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

Abstract Data Types 1

Abstract Data Types 1 Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Abstract Data Types (ADTs) ADT is a set of objects together with a set of operations. Abstract in that implementation of operations

More information

Abstract Data Types 1

Abstract Data Types 1 Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Primitive vs. Abstract Data Types Primitive DT: programmer ADT: programmer Interface (API) data Implementation (methods) Data

More information

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University Abstract Data Types CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues

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

TDDD38 - Advanced programming in C++

TDDD38 - Advanced programming in C++ TDDD38 - Advanced programming in C++ STL II Christoffer Holm Department of Computer and information science 1 Iterators 2 Associative Containers 3 Container Adaptors 4 Lambda Functions 1 Iterators 2 Associative

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

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Standard Template Library

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Standard Template Library CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Standard Template Library 1 Standard Template Library Need to understand basic data types, so we build them ourselves Once understood, we

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

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

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

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

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory C++ 프로그래밍실습 Visual Studio 2015 Contents STL Exercise Practice1 STL Practice 1-1 : Sets The insert method of set class ensures that the set does not contain duplicate keys Without specified position s.insert(123);

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

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

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

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

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

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

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

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

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

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

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS 1 CSE 100: C++ TEMPLATES AND ITERATORS 2 Announcements Look out for the extra weekend section More on git and C++ (iterators) Live demo by your friendly tutors Not mandatory but it will be fun Bring your

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

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

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

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

Advanced C++ STL. Tony Wong

Advanced C++ STL. Tony Wong Tony Wong 2017-03-25 C++ Standard Template Library Algorithms Sorting Searching... Data structures Dynamically-sized array Queues... The implementation is abstracted away from the users The implementation

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

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

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

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

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

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

Containers: Queue and List. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Queue and List. Jordi Cortadella and Jordi Petit Department of Computer Science Containers: Queue and List Jordi Cortadella and Jordi Petit Department of Computer Science Queue A container in which insertion is done at one end (the tail) and deletion is done at the other end (the

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

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

STL Standard Template Library

STL Standard Template Library STL Standard Template Library September 22, 2016 CMPE 250 STL Standard Template Library September 22, 2016 1 / 25 STL Standard Template Library Collections of useful classes for common data structures

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

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

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

CS 103 Unit 15. Doubly-Linked Lists and Deques. Mark Redekopp

CS 103 Unit 15. Doubly-Linked Lists and Deques. Mark Redekopp 1 CS 103 Unit 15 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 each

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

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

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

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

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

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

Queue Implementations

Queue Implementations Queue Implementations 1 Circular Queues buffer of fixed capacity improvements and cost estimates 2 Deques the double ended queue queue as double linked circular list MCS 360 Lecture 17 Introduction to

More information

Dynamic Data Structures

Dynamic Data Structures Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To

More information

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms Instructor: Douglas Wilhelm Harder Time: 2.5 hours Aides: none 14 pages Final Examination

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

Computational Physics

Computational Physics Computational Physics numerical methods with C++ (and UNIX) 2018-19 Fernando Barao Instituto Superior Tecnico, Dep. Fisica email: fernando.barao@tecnico.ulisboa.pt Computational Physics 2018-19 (Phys Dep

More information

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two

More information

CSCI 104 Binary Trees / Priority Queues / Heaps. Mark Redekopp Michael Crowley

CSCI 104 Binary Trees / Priority Queues / Heaps. Mark Redekopp Michael Crowley CSCI 04 Binary Trees / Priority Queues / Heaps Mark Redekopp Michael Crowley Trees Definition: A connected, acyclic (no cycles) graph with: A root node, r, that has 0 or more subtrees Exactly one path

More information

Concurrent Data Structures in C++ CSInParallel Project

Concurrent Data Structures in C++ CSInParallel Project Concurrent Data Structures in C++ CSInParallel Project July 26, 2012 CONTENTS 1 Concurrent Data Structures in C++: Web crawler lab 1 1.1 Your goals................................................ 1 1.2

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

STL. Prof Tejada Week 14

STL. Prof Tejada Week 14 STL Prof Tejada Week 14 Standard Template Library (STL) What is the STL? A generic collection of commonly used data structures and algorithms In 1994, STL was adopted as a standard part of C++ Why used

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

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

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

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

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions 1. You are given a map that associates strings with lists of strings. The definition is: map words; Write

More information

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University (8 1) Container Classes & Class Templates D & D Chapter 18 Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University Key Concepts Class and block scope Access and utility functions

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

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this Lecture Notes Array Review An array in C++ is a contiguous block of memory. Since a char is 1 byte, then an array of 5 chars is 5 bytes. For example, if you execute the following C++ code you will allocate

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

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

pointers + memory double x; string a; int x; main overhead int y; main overhead

pointers + memory double x; string a; int x; main overhead int y; main overhead pointers + memory computer have memory to store data. every program gets a piece of it to use as we create and use more variables, more space is allocated to a program memory int x; double x; string a;

More information

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it Reference LearnCPP.com has many excellent C++ tutorials The auto keyword In C++11, the meaning of the auto keyword has changed, and it is now a useful declaration feature. Consider: double d = 5.0; If

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

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

C++ Programming Chapter 7 Pointers

C++ Programming Chapter 7 Pointers C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE Chapter 1 : What is an application of linear linked list data structures? - Quora A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

Name: 1 stack<int> s; 2 s.push(9) 3 s.push(5) 4 s.push(10) 5 s.push(1) 6 s.pop() 7 s.pop() 8 s.push(0) 9 s.pop() 10 s.pop() 11 s.

Name: 1 stack<int> s; 2 s.push(9) 3 s.push(5) 4 s.push(10) 5 s.push(1) 6 s.pop() 7 s.pop() 8 s.push(0) 9 s.pop() 10 s.pop() 11 s. 1. (5 points) Determine the stack contents at the points indicated below during the following operations on the stack ADT. Write down the stack contents after the operation on the given line is executed.

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

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

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

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

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

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

I source_beg, source_end; // defines a range of values in a source container // defines the beginning of a range in a destination container

I source_beg, source_end; // defines a range of values in a source container // defines the beginning of a range in a destination container Generic Algorithms We have encountered and put to use the concept of generic classes, particularly generic containers. Generic containers could be characterized as implementations of ADTs that are re usable

More information

G Programming Languages Spring 2010 Lecture 11. Robert Soulé, New York University

G Programming Languages Spring 2010 Lecture 11. Robert Soulé, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 11 Robert Soulé, New York University 1 Review Last week Constructors, Destructors, and Assignment Operators Classes and Functions: Design and Declaration

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

CPSC 260 Data Structures and Algorithms for Computer Engineers Linked Lists!

CPSC 260 Data Structures and Algorithms for Computer Engineers Linked Lists! CPSC 260 Data Structures and Algorithms for Computer Engineers Linked Lists! Winter 2013 Instructor: Hassan Khosravi Problems with Arrays and Vectors With arrays and vectors you are allocated a large space.

More information

Data Structures - CSCI 102. CS102 Hash Tables. Prof. Tejada. Copyright Sheila Tejada

Data Structures - CSCI 102. CS102 Hash Tables. Prof. Tejada. Copyright Sheila Tejada CS102 Hash Tables Prof. Tejada 1 Vectors, Linked Lists, Stack, Queues, Deques Can t provide fast insertion/removal and fast lookup at the same time The Limitations of Data Structure Binary Search Trees,

More information

Sequence Containers. Cristian Cibils

Sequence Containers. Cristian Cibils Sequence Containers Cristian Cibils (ccibils@stanford.edu) The Design of C++ Classes & Inheritance Algorithms Iterators Templates Containers Streams Atomic Types Structs A struct is an easy way to bundle

More information

A Standard flat_map. 1 Revisions. 2 Introduction. 3 Motivation and Scope. 1.1 Changes from R Changes from R0

A Standard flat_map. 1 Revisions. 2 Introduction. 3 Motivation and Scope. 1.1 Changes from R Changes from R0 A Standard flat_map Document Number: P0429R2 Date: 2016-08-31 Reply to: Zach Laine whatwasthataddress@gmail.com Audience: LWG/LEWG 1 Revisions 1.1 Changes from R1 Add deduction guides. Change value_type

More information