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

Size: px
Start display at page:

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

Transcription

1 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 across a broad spectrum of client programs. There is another equally important component to generic programming, generic algorithms. A generic algorithm is an implementation of an algorithm that is re usable across a broad spectrum of containers. The key idea facilitating generic algorithms in C++ is the iterator. By writing algorithm implementations interacting with iterators rather than directly with containers, the code can be applied directly to any container whose iterators satisfy the needs of the algorithm. Iterators form the interface between a generic algorithm and a container. Generic Copy The interfacing of an algorithm with a container is accomplished by using iterators as template parameters for the algorithm. This slide shows a typical example, the generic copy algorithm. The template parameters are "I" and "J". The algorithm uses local variables of these types: I source_beg, source_end; // defines a range of values in a source container J dest_beg; // defines the beginning of a range in a destination container and procedes to copy elements from the source range to the target range using a loop: while (source_beg!= source_end) *dest_beg++ = *source_beg++; This dense but efficient code is equivalent to the following: i = source_beg; j = dest_beg; while (i!= source_end) *j = *i; // assign value *i to *j ++i; // increment i ++j; // increment j There is no purpose served (other than explanatory) by declaring extra local variables in the second version, and the postfix increment calls in the first version effect the post assignment increment of both iterators in the second version. This template function can be invoked whenever containers have iterators with the operations *() and ++(int) defined. Thus we can invoke the function for Vector, List, Deque, or ordinary arrays (whose pointers satisfy the same conditions). Given that we have declarations Vector <sometype> V; // a vector object List <sometype> L; // a list object Deque <sometype> D; // a deque object sometype * A[size]; // an array and all containers have size size, the function can be invoked to copy elements from any one of the containers to another, as in the following examples: g_copy (V.Begin(), V.End(), L.Begin()); // copies V to L g_copy (L.Begin(), L.End(), D.Begin()); // copies L to D g_copy (D.Begin(), D.End(), A); // copies D to A g_copy (A, A + size, L.Begin()); // copies A to L The actual code for g_copy() is re used across all four container types. Generic Find This is the classic sequential search algorithm introduced in Chapter 7, converted into a generic algorithm. The input to the algorithm consists of iterarors defining a range of values. The algorithm searches through the range sequentially for a match to t. As soon as success is achieved an iterator pointing to the location of t is returned. Return of the End() iterator (generally an invalid iterator) indicates failure of the search. The generic find algorithm can be invoked for any range in a container whose iterators have operators *() and ++(). 1/15

2 Assume the following container declarations: Vector <sometype> V; // a vector object List <sometype> L; // a list object Deque <sometype> D; // a deque object sometype A[size]; // an array and the following iterator declarations: Vector <sometype>::iterator Vitr; // a vector iterator List <sometype>::iterator Litr; // a list iterator Deque <sometype>::iterator Ditr; // a deque iterator sometype * Aitr; // a pointer (array iterator) Then generic find can be invoked as follows: Litr = g_find (L.Begin(), L.End(), t) // location of t in List L Vitr = g_find (V.Begin(), V.End(), t) // location of t in Vector V Ditr = g_find (D.Begin(), D.End(), t) // location of t in Deque D Aitr = g_find (A, A + size, t) // location of t in array A Generic Max This algorithm, whose implementation is shown on the slide, returns the location of the largest element of a range in a container (the first largest, if there is more than one). The range is given by a begin/end iterator pair, and the location is returned also as an iterator. The code for this implementation is equivalent to the following more readable, less compact version: template <class I> I g_max_element (I beg, I end) if (beg == end) return end; I max; max = beg; ++beg; while (beg!= end) if (*max < *beg) max = beg; ++beg; return max; This generic algorithm can be invoked for any range in a container whose iterators have operators *() and ++(). Assume the container declarations as above and the following iterator declarations: Vector <sometype>::iterator Vitr; // a vector iterator List <sometype>::iterator Litr; // a list iterator Deque <sometype>::iterator Ditr; // a deque iterator sometype * Aitr; // a pointer (array iterator) Then generic max can be invoked as follows: Vitr = g_max_element (V.Begin(), V.End()) // max element of V = *Vitr Litr = g_max_element (L.Begin(), L.End()) // max element of L = *Litr Ditr = g_max_element (D.Begin(), D.End()) // max element of D = *Ditr Aitr = g_max_element (A, A + size) // max element of A = *Aitr Again, the actual code for the generic algorithm is re used for four different kinds of containers Generic Algorithms and Predicate Objects 2/15

3 Function objects are used extensively by generic algorithms. Predicate objects, in particular, are used when non default boolean operations are needed. For example, there is an alternate form of generic max that imports a user definable notion of order: template <class I, class P> I g_max_element (I beg, I end, const P& p) if (beg == end) return end; I max(beg); while (++beg!= end) if (p(*max, *beg)) max = beg; return max; A predicate object P p is passed to the algorithm and used in place of operator <() to determine the maximum value in the incoming range. The following are example uses of this version: TGreaterThan <sometype> gt; Vitr = g_max_element (V.Begin(), V.End(), gt) // min element of V = *Vitr Litr = g_max_element (L.Begin(), L.End(), gt) // min element of L = *Litr Ditr = g_max_element (D.Begin(), D.End(), gt) // min element of D = *Ditr Aitr = g_max_element (A, A + size, gt) // min element of A = *Aitr Note that this invocation actually finds the minimum value, because of the substitution of greater than for less than. Generic Algorithms and Function Objects Non boolean function objects are also used in some algorithms. One of the most used is g_for_each, shown in the slide, which applies a function object to every element in a specified range. Generic For Each is an algorithm that applies a function object to each element in a range. template <class I, class F> F g_for_each (I beg, I end, F f) while (beg!= end) f(*(beg++)); return f; The function class F may be anything that may be applied to elements of type t. It could count things, accumulate a value over the range (sum or product, for example), or modify all the objects in the range. Here is an example that conditionally modifies the elements in a range, using the MakeUpperCase function class from the previous chapter: List<char> L; //... code putting elements into L MakeUpperCase muc; g_for_each (L.Begin(), L.End(), muc); // converts every element of L to upper case After the call to g_for_each, all alpha characters in L are upper case. Generic For Each The generic algorithm g_for_each, introduced in the previous slide, is unusual in that it has a return value: a copy of the function object passed into the algorithm is returned as a value. For stateless function objects this has little utility, but for function objects that modify their own data as they are used, this can be very useful. A "smart" version of MakeUpperCase is shown in this slide; SmartMakeUpperCase objects keep count of the number of times a letter is converted from lower to upper case. By returning a copy of this function object, a running count of the number of lower case letters converted to upper case is preserved. This example is somewhat contrived, but it illustrates some of the power of "smart" functions and how the generic for each algorithm can facilitate their utility. Here is another example that accumulates values over a range. This function class is defined as a template class so that it may be applied to any type for which operator +() is defined. 3/15

4 Note that template <typename T> class Addemup public: T sum; Addemup (const T& init) : sum(init) void operator () (const T& t) sum += t; ; List<float> L; //... code putting elements into L Addemup adder(0); adder = g_for_each (L.Begin(), L.End(), adder); std::cout << adder.sum; 1. adder is passed by value 2. The state of the local copy of adder is modified during the call to g_for_each 3. adder is returned by value, as modified The result output to screen is the sum of all elements in the range. Testing Generic Algorithms /* fga.cpp functionality test of generic algorithms using List<T>, Vector<T>, Deque<T>, and arrays of T typedef char ElementType; const char* e_t = "char"; List < ElementType > L; // a list Vector < ElementType > V; // a vector Deque < ElementType > Q; // a deque ElementType * A; // an array List < ElementType >::Iterator Litr, Lloc; Vector < ElementType >::Iterator Vitr, Vloc; Deque < ElementType >::Iterator Qitr, Qloc; ElementType * Aitr, * Aloc; ElementType e, s; // entry, sentinal unsigned int i, p, size; // define the list L somehow, and properly size all containers //... // copy to vector, deque, and array g_copy (L.Begin(), L.End(), V.Begin()); g_copy (V.Begin(), V.End(), Q.Begin()); g_copy (Q.Begin(), Q.End(), A); //... // g_min_element Lloc = g_min_element(l.begin(), L.End()); Vloc = g_min_element(v.begin(), V.End()); Qloc = g_min_element(q.begin(), Q.End()); Aloc = g_min_element(a, A + size); //... // g_max_element 4/15

5 Lloc = g_max_element(l.begin(), L.End()); Vloc = g_max_element(v.begin(), V.End()); Qloc = g_max_element(q.begin(), Q.End()); Aloc = g_max_element(a, A + size); // g_find (sequential search each container for value e): Lloc = g_find (L.Begin(), L.End(), e); Vloc = g_find (V.Begin(), V.End(), e); Qloc = g_find (Q.Begin(), Q.End(), e); Aloc = g_find (A, A + size, e); // g_for_each (apply a SmartMakeUpperCase object to each element of each container): SmartMakeUpperCase smuc; smuc = g_for_each(l.begin(), L.End(), smuc); smuc = g_for_each(v.begin(), V.End(), smuc); smuc = g_for_each(q.begin(), Q.End(), smuc); smuc g_for_each(a, A + size, smuc); // output the number of conversions from lower case to upper case: cout << "Number of case conversions: " << smuc.count; Testing Generic Algorithms The following is taken from a test/demonstration program that calls various generic algorithms for four different container classes. /* fga.cpp functionality test of generic algorithms using List<T>, Vector<T>, Deque<T>, and arrays of T typedef char ElementType; const char* e_t = "char"; List < ElementType > L; // a list Vector < ElementType > V; // a vector Deque < ElementType > Q; // a deque ElementType * A; // an array List < ElementType >::Iterator Litr, Lloc; Vector < ElementType >::Iterator Vitr, Vloc; Deque < ElementType >::Iterator Qitr, Qloc; ElementType * Aitr, * Aloc; ElementType e, s; // entry, sentinal unsigned int i, p, size; // define the list L somehow, and properly size all containers //... // copy to vector, deque, and array g_copy (L.Begin(), L.End(), V.Begin()); g_copy (V.Begin(), V.End(), Q.Begin()); g_copy (Q.Begin(), Q.End(), A); //... // g_min_element Lloc = g_min_element(l.begin(), L.End()); Vloc = g_min_element(v.begin(), V.End()); Qloc = g_min_element(q.begin(), Q.End()); Aloc = g_min_element(a, A + size); //... // g_max_element Lloc = g_max_element(l.begin(), L.End()); Vloc = g_max_element(v.begin(), V.End()); Qloc = g_max_element(q.begin(), Q.End()); Aloc = g_max_element(a, A + size); 5/15

6 // g_find (sequential search each container for value e): Lloc = g_find (L.Begin(), L.End(), e); Vloc = g_find (V.Begin(), V.End(), e); Qloc = g_find (Q.Begin(), Q.End(), e); Aloc = g_find (A, A + size, e); // g_for_each (apply a SmartMakeUpperCase object to each element of each container): SmartMakeUpperCase smuc; smuc = g_for_each(l.begin(), L.End(), smuc); smuc = g_for_each(v.begin(), V.End(), smuc); smuc = g_for_each(q.begin(), Q.End(), smuc); smuc g_for_each(a, A + size, smuc); // output the number of conversions from lower case to upper case: cout << "Number of case conversions: " << smuc.count; The source code for this demonstration program is distributed in file tests/fga.cpp. An executable version is also available in area51/fga.x. Generic Insertion Sort A simple generic insertion sort algorithm is presented in two versions, one using the default order determined by int operator < (const T&,const T& ) and the other taking an order predicate class in through the template parameter. template < class BidirectionalIterator > void g_insertion_sort (BidirectionalIterator beg, BidirectionalIterator end) BidirectionalIterator I, J, K; typename BidirectionalIterator::ValueType t; for (I = beg; I!= end; ++I) t = *I; for (K = I, J = K ; J!= beg && t < *K; J, K) *J = *K; *J = t; template < class BidirectionalIterator, class Comparator > void g_insertion_sort (BidirectionalIterator beg, BidirectionalIterator end, const Comparator& cmp) BidirectionalIterator I, J, K; typename BidirectionalIterator::ValueType t; for (I = beg; I!= end; ++I) t = *I; for (K = I, J = K ; J!= beg && cmp(t,*k); J, K) *J = *K; *J = t; Here are sample uses of both these versions of insertion sort: List<int> L;... g_insertion_sort(l.begin(), L.End()); g_insertion_sort(l.begin(), L.End(), GreaterThan); // sorts in increasing order // sorts in decreasing order One interesting point illustrated by g_insertion_sort is the way the value type of the range is needed and accessed. For this reason, these algorithms will not compile for raw pointers. To make them work for arrays, we need to specialize the templates, as follows: // specialization for pointers template < typename T > void g_insertion_sort (T* beg, T* end) 6/15

7 T *I, *J, *K; T t; for (I = beg; I!= end; ++I) t = *I; for (K = I, J = K ; J!= beg && t < *K; J, K) *J = *K; *J = t; // specialization for pointers template < typename T, class Comparator > void g_insertion_sort (T* beg, T* end, const Comparator& cmp) T *I, *J, *K; T t; for (I = beg; I!= end; ++I) t = *I; for (K = I, J = K ; J!= beg && cmp(t,*k); J, K) *J = *K; *J = t; Now one can use the same generic algorithm for vectors and arrays, as in: Vector<int> V; int A[size];... g_insertion_sort(v.begin(), V.End()); g_insertion_sort(a, A + size); // sorts vector V // sorts array A The technique relies on the feature of C++ that allows specializations of templates. When the compiler encounters more than one way to instantiate a template, it chooses the most specific. Thus, when we apply generic insertion sort to a range specified by pointers, there are two possible templates that fir. The specialization is the more specific, so it is chosen. Generic Binary Search There are six versions of binary search available as generic algorithms: two versions each of lower_bound, upper_bound, and binary_search. One version of each uses standard less_than order and one uses a predicate object to determine order. These algorithms require random access iterators (operator [] () and "pointer" arithmetic) and also require that the range of search be ordered (either by operator <() or by the predicate object passed in as a parameter). The predicate version of lower_bound is shown in the slide. It is important to understand this implementation in detail, including: The use of pointer arithmetic Proof of correctness (as given previously for the array based version) Proof of complexity (also as given previously) All six versions of generic binary search are distributed in tcpp/gbsearch.h. Headers are presented at the end of this chapter. Testing Generic Sort and Binary Search /* fgss.cpp "generic sort & search" functionality test of generic sort and binary search on Vector<T>, Deque<T>, and arrays of T #include <iostream.h> #include <vector.cpp> 7/15

8 #include <deque.cpp> #include <compare.cpp> #include <gsort.h> #include <gbsearch.h> #include <genalg.h> int main() typedef char ElementType; const char* e_t = "char"; typedef TLessThan <ElementType> PredicateType1; typedef TGreaterThan <ElementType> PredicateType2; Vector < ElementType > V; // a vector Deque < ElementType > Q; // a deque ElementType * A; // an array PredicateType1 LT; // predicate object PredicateType2 GT; // predicate object Vector < ElementType > ::Iterator Vitr, Vloc; Deque < ElementType > ::Iterator Qitr, Qloc; ElementType * Aitr, * Aloc; ElementType e, s; // entry, sentinal unsigned int i, size; cout << "Begin test of g_insertion_sort and g_binary_search < " << e_t << " >\n" << "Enter sentinal: "; cin >> s; cout << "Enter elements ('" << s << "' to end): "; cin >> e; while (e!= s) V.PushBack(e); cin >> e; cout << "V as entered: " << V << '\n'; // copy to deque size = V.Size(); for (i = 0; i < size; ++i) if (i%2) Q.PushFront(V[i]); else Q.PushBack(V[i]); cout << "Q as copied: // copy to array A = new ElementType [size]; for (i = 0; i < size; ++i) A[i] = V[i]; cout << "A as copied: "; for (i = 0; i < size; ++i) cout << A[i]; cout << '\n'; " << Q << '\n'; // apply generic insertion sort to each container, display, and recopy g_insertion_sort(v.begin(), V.End(), GT); cout << "g_insertion_sort(v,>): " << V << '\n'; g_copy(q.begin(), Q.End(), V.Begin()); g_insertion_sort(q.begin(), Q.End(), GT); cout << "g_insertion_sort(q,>): " << Q << '\n'; g_copy(v.begin(), V.End(), Q.Begin()); 8/15

9 g_insertion_sort(a, A + size, GT); cout << "g_insertion_sort(a,>): "; for (i = 0; i < size; ++i) cout << A[i]; cout << '\n'; g_copy(q.begin(), Q.End(), A); cout << "V as recopied: cout << "Q as recopied: cout << "A as recopied: for (i = 0; i < size; ++i) cout << A[i]; cout << '\n'; " << V << '\n'; " << Q << '\n'; "; // apply generic insertion sort again to each container and display g_insertion_sort(v.begin(), V.End()); cout << "g_insertion_sort(v): " << V << '\n'; g_insertion_sort(q.begin(), Q.End()); cout << "g_insertion_sort(q): " << Q << '\n'; g_insertion_sort(a, A + size, LT); cout << "g_insertion_sort(a,<): "; for (i = 0; i < size; ++i) cout << A[i]; cout << '\n'; // now do binary search while(1) cout << "Enter search value ('" << s << "' to quit): "; cin >> e; if (e == s) break; Vloc = g_lower_bound(v.begin(), V.End(), e, LT); cout << "V = " << V << '\n'; cout << " "; for (Vitr = V.Begin(); Vitr!= Vloc; ++Vitr) cout << ' '; cout << "^lb\n"; Vloc = g_upper_bound(v.begin(), V.End(), e, LT); cout << "V = " << V << '\n'; cout << " "; for (Vitr = V.Begin(); Vitr!= Vloc; ++Vitr) cout << ' '; cout << "^ub\n"; Qloc = g_lower_bound(q.begin(), Q.End(), e, LT); cout << "Q = " << Q << '\n'; cout << " "; for (Qitr = Q.Begin(); Qitr!= Qloc; ++Qitr) cout << ' '; cout << "^lb\n"; Qloc = g_upper_bound(q.begin(), Q.End(), e, LT); cout << "Q = " << Q << '\n'; cout << " "; for (Qitr = Q.Begin(); Qitr!= Qloc; ++Qitr) cout << ' '; cout << "^ub\n"; Aloc = g_lower_bound(a, A + size, e, LT); cout << "A = "; for (Aitr = A; Aitr!= A + size; ++Aitr) cout << *Aitr; cout << '\n'; cout << " "; for (Aitr = A; Aitr!= Aloc; ++Aitr) cout << ' '; cout << "^lb\n"; Aloc = g_upper_bound(a, A + size, e, LT); cout << "A = "; for (Aitr = A; Aitr!= A + size; ++Aitr) cout << *Aitr; cout << '\n'; cout << " "; for (Aitr = A; Aitr!= Aloc; ++Aitr) cout << ' '; cout << "^ub\n"; 9/15

10 cout << e << " is "; if (!g_binary_search(v.begin(), V.End(), e, LT)) cout << "not "; cout << "in V\n"; cout << e << " is "; if (!g_binary_search(q.begin(), Q.End(), e, LT)) cout << "not "; cout << "in Q\n"; cout << e << " is "; if (!g_binary_search(a, A + size, e, LT)) cout << "not "; cout << "in A\n"; cout << "End test of g_insertion_sort/g_binary_search < " << e_t << " >\n"; return 0; (See tests/fgss.cpp.) Generic Algorithms Catalog Generic algorithms fall into functional categories differentiated by their assumptions and runtime characteristics and are located in separate files by category. The following table shows the categories and the file names (duplicated in the slide): category iterator types container preconditions file comments (n = size of input) utility input or output none genalg.h sequential (iterative) algorithms O(n) insertion sort bidirectional none gsort.h in place, stable, O(n 2 ) set algorithms input or output totally ordered (sorted) gset.h binary search heap sort heap algorithms random access random access random access totally ordered (sorted) gbsearch.h O(log n) sequential (iterative) set algorithms O(n) none gheap.h in place, unstable, O(n log n) partially ordered (POT) gheap.h push and pop heap O(log n) The following is a listing of all of the generic algorithms in these files, by category. Namespaces are not shown. General Utility Algorithms /* genalg.h General utility generic algorithms for non random access iterators I, J iterator classes (usually I = input iterator, J = output) T ValueType P predicate class (may be unary or binary, depending on context) F function class (context determined) template <class I, typename T> void g_fill (I beg, I end, const T& t) template <class I, typename T> void g_fill_n (I beg, int n, const T& t) template <class I, typename T> void g_fill_n (I beg, unsigned int n, const T& t) template <class I, class J> void g_copy (I source_beg, I source_end, J dest_beg) template <class I, class J> void g_copy_backward (I source_beg, I source_end, J dest_beg) 10/15

11 template <class I> I g_min_element (I beg, I end) template <class I, class P> I g_min_element (I beg, I end, const P& p) template <class I> I g_max_element (I beg, I end) template <class I, class P> I g_max_element (I beg, I end, const P& p) template <class I, typename T> I g_find (I beg, I end, const T& t) template <class I, class P> I g_find_if (I beg, I end, const P& p) template <class I, class F> F g_for_each(i beg, I end, F f) Insertion Sort Algorithms /* gsort.h generic sort algorithm applicable to a range specified by iterators implementing insertion sort algoriithm template < class BidirectionalIterator > void g_insertion_sort (BidirectionalIterator beg, BidirectionalIterator end); template < class BidirectionalIterator, class Comparator > void g_insertion_sort (BidirectionalIterator beg, BidirectionalIterator end, const Comparator& cmp); // specialization for pointers template < typename T > void g_insertion_sort (T* beg, T* end); // specialization for pointers template < typename T, class Comparator > void g_insertion_sort (T* beg, T* end, const Comparator& cmp); Set Algorithms /* gset.h generic set algorithms All of these algorithms have a common set of preconditions, as follows: 1. I1, I2 are input iterators and I3 is output iterator. (I3 may be an insert iterator.) 2. P is a predicate order class defined on the input ranges (transitive, anti reflexive, and dichotomous) 3. The two input ranges are sorted using p where present and < otherwise 4. The input range ValueType is convertible to the output range ValueType A common postcondition is: the output range is sorted using p where present or < otherise template <class I1, class I2, class I3, class P> void g_set_union(i1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest, P p) // range3 = range1 union range2 template <class I1, class I2, class I3> void g_set_union(i1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest) // default order version uses operator < 11/15

12 template <class I1, class I2, class I3, class P> void g_set_merge (I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest, const P& p) // range3 = range1 merge range2 template <class I1, class I2, class I3> void g_set_merge (I1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest) // default order version uses operator < () template <class I1, class I2, class I3, class P> void g_set_intersection(i1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest, const P& p) // range3 = range1 intersection range2 template <class I1, class I2, class I3> void g_set_intersection(i1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest) // default order version uses operator <() template <class I1, class I2, class I3, class P> void g_set_difference(i1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest, const P& p) // range3 = range1 difference range2 template <class I1, class I2, class I3> void g_set_difference(i1 beg1, I1 end1, I2 beg2, I2 end2, I3 dest) // default order version uses operator <() template <class I1, class I2, class P> int g_subset_of(i1 beg1, I1 end1, I2 beg2, I2 end2, P p) // returns true iff range 1 is contained in range 2 template <class I1, class I2> int g_subset_of (I1 beg1, I1 end1, I2 beg2, I2 end2) // default version uses operator <() Binary Search Algorithms /* gbsearch.h Generic binary search algorithms for random access iterators These algrithms take parameters of type I, T, and optionally a third parameter of type P. about I ======= I is a random access iterator type; this means that the bracket operator T& operator [] (unsigned int); is defined and the usual "pointer" arithmetic operations are defined: I& operator += (long n); I& operator = (long n); I operator + (long n) const; long operator (const I& I2) const; Examples include: ordinary array iterators (pointers); Vector<T>::Iterator; Dequeue<T>::Iterator; about T ======= T is the ValueType of the iterator I about P ======= P is a predicate class used for order; an object LessThan of class P 12/15

13 has the function evaluation operator overloaded with the prototype bool operator () (const T&, const T&); Note that P must be used to order the elements so that P can work as a search condition. g_lower_bound() and g_upper_bound() implement binary search for random access iterators. It is assumed that the elements of iteration are in nondecreasing order (using operator < or an optional predicate object). g_lower_bound returns an iterator to the first location containing the search value if found, and the location where it would be otherwise. g_upper_bound returns an iterator to the first location whose element is greater than the search value if such exists or the end iterator otherwise. I.e. (assuming L = lower bound and U = upper bound): if t is in the collection: t == *L, t < *U, and L and U are the smallest iterators in the sequence with these properties; thus, beg = L and end = U mark the range of t in the collection; if t is not in the collection: L == U, and these iterators point to the location where t could be inserted and maintain nondecreasing order. bool binary_search() uses the same algorithm, returning true iff found. All these versions of binary search run in time O(log size). #include <compare.cpp> template <class I, typename T, class P> I g_lower_bound (I beg, I end, const T& val, const P& LessThan) // pre: I is a random access iterator (operator [] and "pointer" arithmetic) // I has ValueType T // beg + n = end for some n >= 0 // beg[0]... beg[n 1] are in non decreasing order using LessThan // post: no state is changed // return: itr = beg + i, where beg[i 1] < val <= beg[i]; or // itr = end if no such i exists template <class I, typename T, class P> I g_upper_bound (I beg, I end, const T& val, const P& LessThan) // pre: I is a random access iterator (operator [] and "pointer" arithmetic) // I has ValueType T // beg + n = end for some n >= 0 // beg[0]... beg[n 1] are in non decreasing order using LessThan // post: no state is changed // return: itr = beg + i, where beg[i 1] <= val < beg[i]; or // itr = end if no such i exists template <class I, typename T, class P> int g_binary_search (I beg, I end, const T& val, const P& LessThan) // pre: I is a random access iterator (operator [] and "pointer" arithmetic) // I has ValueType T // beg + n = end for some n >= 0 // beg[0]... beg[n 1] are in non decreasing order using LessThan // post: no state is changed // return: true if found, false if not found template <class I, typename T> I g_lower_bound (I beg, I end, const T& val) template <class I, typename T> I g_upper_bound (I beg, I end, const T& val) template <class I, typename T> int g_binary_search (I beg, I end, const T& val) 13/15

14 Heap Algorithms /* gheap.h The generic heap algorithms These algorithms use three types I, P, T but only two template parameters <I,P> I: a random access iterator class P: a predicate class for T T: the ValueType for underlying container on which I iterates A random access iterator I is one for which the bracket operator T& operator [] (unsigned int ); is defined and for which "pointer" arithmetic is defined. Examples include: ordinary arrays of T; Vector<T>; and Deque<T> A predicate class is one for which the function evaluation operator bool operator () (const T&, const T&); is defined. An object LessThan of class P is used to determine order in T: "LessThan (a,b) == true" iff "a < b" The type T is not explicitly mentioned in the template (or parameter) list for g_heap_sort, but it is needed for the call to g_xc. #include <compare.cpp> template <class I, class P> void g_heap_sort (I beg, I end, const P& LessThan) // Implements heapsort for the iterators // Heapsort has the following attributes: // * fast: runtime O(size*log(size)) // * in place: the sort happens in the space implied by the iterators // * NOT stable the original order of objects a, b may change when // a == b // pre: I is a random access iterator class (operator [] and "pointer" arithmetic) // T is the ValueType of I // P is a predicate class for type T // post: the range of values specified by the iterators is ordered LessThan, // i.e., LessThan(a,b) == true ==> a comes before b in the container template <class I> void g_heap_sort (I beg, I end) // the default order version template <class I, class P> void g_push_heap (I beg, I end, const P& LessThan) // Defn: a < b means LessThan(a,b) == true // Defn: POT means parent >= children // Pre: the range [beg,end) is valid // if the range [beg,end 1) is valid (i.e., [beg,end) is non void) // then the range [beg,end 1) is a POT // Post: the range [beg,end) is a POT template <class I> void g_push_heap (I beg, I end) // the default order version template <class I, class P> void g_pop_heap (I beg, I end, const P& LessThan) // Defn: a < b means LessThan(a,b) == true // Defn: POT means parent >= children // Pre: the range [beg,end) is valid // the range [beg,end 1) is valid (i.e., [beg,end) is non void) // the range [beg,end) is a POT // Post: the largest element beg[0] is removed from the range [beg,end 1) // the range [beg,end 1) is a POT 14/15

15 // the old largest element (i.e., beg[0]) is copied to // the end of the old range (i.e., to beg[end beg 1]) template <class I> void g_pop_heap (I beg, I end) // the default order version template <typename T> void g_xc (T& t1, T& t2) 15/15

This chapter serves mainly to gather and organize information about iterators. Some new concepts are also introduced for completeness.

This chapter serves mainly to gather and organize information about iterators. Some new concepts are also introduced for completeness. Iterators Overview We have introduced, used, built, and studied iterators in several contexts, including List, TDeque, and TVector. We have seen that ordinary pointers also can be thought of as iterators

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

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

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

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

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

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

Final Exam Solutions PIC 10B, Spring 2016

Final Exam Solutions PIC 10B, Spring 2016 Final Exam Solutions PIC 10B, Spring 2016 Problem 1. (10 pts) Consider the Fraction class, whose partial declaration was given by 1 class Fraction { 2 public : 3 Fraction ( int num, int den ); 4... 5 int

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

G52CPP C++ Programming Lecture 18

G52CPP C++ Programming Lecture 18 G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know

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

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

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

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

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

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

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

14. Pointers, Algorithms, Iterators and Containers II

14. Pointers, Algorithms, Iterators and Containers II Recall: Pointers running over the Array Beispiel 14. Pointers, Algorithms, Iterators and Containers II Iterations with Pointers, Arrays: Indices vs. Pointers, Arrays and Functions, Pointers and const,

More information

Creating a C++ Program

Creating a C++ Program Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. 1 Creating a C++ Program created using an

More information

Writing Generic Functions. Lecture 20 Hartmut Kaiser hkaiser/fall_2013/csc1254.html

Writing Generic Functions. Lecture 20 Hartmut Kaiser  hkaiser/fall_2013/csc1254.html Writing Generic Functions Lecture 20 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2013/csc1254.html Code Quality Programming Principle of the Day Minimize Coupling - Any section

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

/ binary_search example #include <iostream> // std::cout #include <algorithm> // std::binary_search, std::sort #include <vector> // 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

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

G52CPP C++ Programming Lecture 18. Dr Jason Atkin G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that

More information

Largest Online Community of VU Students

Largest Online Community of VU Students WWW.VUPages.com http://forum.vupages.com WWW.VUTUBE.EDU.PK Largest Online Community of VU Students MIDTERM EXAMINATION SEMESTER FALL 2003 CS301-DATA STRUCTURE Total Marks:86 Duration: 60min Instructions

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

15. Pointers, Algorithms, Iterators and Containers II

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

More information

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

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type. CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

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

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

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

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

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2305/lab33.C Input: under control of main function Output: under control of main function Value: 3 The Shell sort, named after its inventor Donald Shell, provides a simple and efficient

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

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Science Midterm 3 Fall, Points Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do

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

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

Patterns: Working with Arrays

Patterns: Working with Arrays Steven Zeil October 14, 2013 Outline 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates

More information

the Stack stack ADT using the STL stack are parentheses balanced? algorithm uses a stack adapting the STL vector class adapting the STL list class

the Stack stack ADT using the STL stack are parentheses balanced? algorithm uses a stack adapting the STL vector class adapting the STL list class the Stack 1 The Stack Abstract Data Type stack ADT using the STL stack 2 An Application: Test Expressions are parentheses balanced? algorithm uses a stack 3 Stack Implementations adapting the STL vector

More information

Standard Template Library

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

More information

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

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

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

Priority Queues (Heaps)

Priority Queues (Heaps) Priority Queues (Heaps) 1 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted order. Often we collect a set of items and process the

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

CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010

CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010 CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010 Question 1 Part 1, Program A: This program reads integers on standard input and stops when it encounters EOF or a non-integer. It

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

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit.

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit. C++ Basics January 19, 2012 Brian A. Malloy Slide 1 of 24 1. Many find Deitel quintessentially readable; most find Stroustrup inscrutable and overbearing: Slide 2 of 24 1.1. Meyers Texts Two excellent

More information

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science Containers: Stack Jordi Cortadella and Jordi Petit Department of Computer Science The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list.

More information

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

SEMANTIC ANALYSIS TYPES AND DECLARATIONS SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether

More information

Lab 6. Out: Wednesday 9 March 2005

Lab 6. Out: Wednesday 9 March 2005 CS034 Intro to Systems Programming Doeppner & Van Hentenryck What you ll learn. Lab 6 Out: Wednesday 9 March 2005 Modern C++ comes with a powerful template library, the Standard Template Library, or STL.

More information

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT Containers: Stack The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list. Also known as LIFO Last In, First Out) push insert an element

More information

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Fall 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if

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

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

CS11 Advanced C++ Spring 2018 Lecture 2

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

More information

Arrays and Pointers.

Arrays and Pointers. Arrays and Pointers pm_jat@daiict.ac.in What is an array? First element a 15 8 107 311 187-20 152 11 38 87 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] Name of array Array index Array Declaration

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

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

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Assignment 1: grid. Due November 20, 11:59 PM Introduction CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

When we program, we have to deal with errors. Our most basic aim is correctness, but we must Chapter 5 Errors When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. When

More information

Largest Online Community of VU Students

Largest Online Community of VU Students WWW.VUPages.com WWW.VUTUBE.EDU.PK http://forum.vupages.com Largest Online Community of VU Students MIDTERM EXAMINATION SEMESTER FALL 2003 CS301-DATA STRUCTURE Total Marks:86 Duration: 60min Instructions

More information

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

Computer Science II Lecture 2 Strings, Vectors and Recursion

Computer Science II Lecture 2 Strings, Vectors and Recursion 1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed

More information

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

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

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

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

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

More information

Topics. bool and string types input/output library functions comments memory allocation templates classes

Topics. bool and string types input/output library functions comments memory allocation templates classes C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers

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

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

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy CAAM 420 Fall 2012 Lecture 29 Duncan Eddy November 7, 2012 Table of Contents 1 Templating in C++ 3 1.1 Motivation.............................................. 3 1.2 Templating Functions........................................

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1........ COMP6771 Advanced C++ Programming Week 4 Part Three: Function Objects and 2016 www.cse.unsw.edu.au/ cs6771 2........ Converting Class Types to bool Convenient to use a class object as bool to

More information

Final Exam. Name: Student ID: Section: Signature:

Final Exam. Name: Student ID: Section: Signature: Final Exam PIC 10B, Spring 2016 Name: Student ID: Section: Discussion 3A (2:00 2:50 with Kelly) Discussion 3B (3:00 3:50 with Andre) I attest that the work presented in this exam is my own. I have not

More information

Arrays. Arizona State University 1

Arrays. Arizona State University 1 Arrays CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 8 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

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

Week 8: Operator overloading

Week 8: Operator overloading Due to various disruptions, we did not get through all the material in the slides below. CS319: Scientific Computing (with C++) Week 8: Operator overloading 1 The copy constructor 2 Operator Overloading

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-2: Programming basics II Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428 March

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives 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

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

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

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \ BSc IT C Programming (2013-2017) Unit I Q1. What do you understand by type conversion? (2013) Q2. Why we need different data types? (2013) Q3 What is the output of the following (2013) main() Printf( %d,

More information

CSCI-1200 Data Structures Test 3 Practice Problem Solutions

CSCI-1200 Data Structures Test 3 Practice Problem Solutions 1 Short Answer [ /21] CSCI-1200 Data Structures Test 3 Practice Problem Solutions 1.1 TreeNode Parent Pointers [ /5] In our initial version of the ds set class, the TreeNode object had 3 member variables:

More information

Introduction to C ++

Introduction to C ++ Introduction to C ++ Thomas Branch tcb06@ic.ac.uk Imperial College Software Society October 18, 2012 1 / 48 Buy Software Soc. s Free Membership at https://www.imperialcollegeunion.org/shop/ club-society-project-products/software-products/436/

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

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer

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

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

The Ada Standard Generic Library (SGL)

The Ada Standard Generic Library (SGL) The Ada Standard Generic Library (SGL) Alexander V. Konstantinou Computer Science Graduate Seminar 4/24/96 1 Presentation Overview Introduction (S{T G}L) The C++ Standard Template Library (STL) Ada 95

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

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information