Computer Application and Practice 2: Templates and the Standard Template Library

Size: px
Start display at page:

Download "Computer Application and Practice 2: Templates and the Standard Template Library"

Transcription

1 Computer Application and Practice 2: Templates and the Standard Template Library 2014 Instructor: Young-guk Ha Dept. of Computer Science & Engineering

2 Contents Basics on templates Template classes Template instantiations Standard Template Library (STL) Containers Basic containers Container adaptors Iterators Algorithms 2

3 Template Classes Blueprints for general-purpose classes Template classes are not data-type specific Created with more than one class parameters, which are placeholders for specific data types Also called as parameterized classes Template classes promote code reuse in C++ If we write an Array template class once, we can reuse the template class to create Arrays of any data type Without template classes, we need to write Class IntArray for array of ints Class CharArray for array of chars Class StringArray, 3

4 Without Template Classes Class IntArray Class CharArray Class X-Array Integer Array Character Array X-type Array 4

5 Using Template Classes Class Parameters: int, char, X-type, Template Class Array<param> Class Array<int> Class Array<char> Class Array<X-type> Integer Array Character Array X-type Array 5

6 Declaring Template Classes template<class param1, class param2,...> class class_name {... or Template header template<typename param1, typename param2,...> class class_name {... 6

7 Defining Template Class Methods template<class p1, class p2,...> class class_name { public: return_type method_name(... ) { or template<class p1, class p2,...> return_type class_name<p1, p2,...>::method_name(... ) {... 7

8 class intarray { public: int& operator[](int); intarray(int); ~intarray(); // private: int* a; int size; // ; intarray::intarray(int s) { a = new int[size = s]; // intarray a1(10); class chararray { public: char& operator[](int); chararray(int); ~chararray(); // private: char* a; int size; // ; chararray::chararray(int s) { a = new char[size = s]; // chararray a2(50); Classes vs. Template Classes With template class Array template<class T> class Array { public: T& operator[](int); Array(int); ~Array(); // private: T* a; int size; // ; template<class T> Array<T>::Array(int s) { a = new T[size = s]; // Array<int> a1(10); Array<char> a2(50); Array<string> a3(20); // 8

9 Template Instantiation To use a template class, we must instantiate it with a specific data type A data type must be specified within angled brackets E.g., the previous template class Array template<class T> class Array {... ; If we instantiate Array<T> to Array<double> as follows Array<double> a1(100); // type of a1 is Array<double> Then the compiler replaces occurrences of T in the instantiation with double, thus the declaration T& operator[](int); T* a; are changed into double& operator[](int); double* a; 9

10 Template Instantiation (cont.) Un-instantiated template classes can not create their objects template<class T> class Array {... ; Array a0(50); //***** ERROR: not an instantiation Array<T> a1(50); //***** ERROR: not an instantiation template<class T> Array<T> a2(50); //***** ERROR: not an instantiation Array<int> a3(50); // OK, int instantiation A template class can be instantiated with either a built-in or a user-defined data type // user-defined data type Task class Task {... ; Array<Task> tasks(500); // Task instantiation 10

11 Template Classes in a Parameter List A template class may occur as a data type in a parameter list template<class T> ostream& operator<<(ostream& os, const Array<T>& ar) { for (int i = 0; i < ar.get_size(); i++) os << ar[i] << endl; // built-in << return os;... Array<int> a(3); a[0] = 0; a[1] = 1; a[2] = 2; cout << a; // overloaded <<

12 Function-Style Parameters Parameters for a template class Class parameters A template class MUST have one or more class parameters Function-style parameters May have any number of function-style parameters Data type can be either built-in or user-defined // just using a class parameter template<class T> Array<T>::Array(int s) { a = new T[size = s] Array<double> a1(10); Array<char> a2(50); // using function-style param. s template<class T, int s> Array<T, s>::array() { a = new T[size = s] Array<double, 10> a1; Array<char, 50> a2; Array<float> a3; // ERROR: missing arg. for s 12

13 Standard Template Library (STL) A part of standard C++ library STL has very powerful features in its own right Consists of template classes to provide containers for data and template functions to process data in containers Also has significant impact on the organization of other C++ libraries E.g., Active Template Library (ATL) and Windows Template Library (WTL) 13

14 Basic Components of STL STL s three basic components are containers, algorithms, and iterators Containers Collection of data structures implemented with template classes E.g., vectors, deques, lists, sets, maps, stacks, queues, Algorithms Recipes or procedures for processing containers contents, which are implemented with template functions E.g., sort, copy, reverse, search, merge, permute, Iterators Provides a unified mechanism for accessing contents in containers one at a time (high-level alternatives for looping constructs such as for and while) To move through containers from front to back, from back to front, in either direction, and randomly In any case, STL algorithms use iterators to process containers 14

15 Advantages of STL STL becomes increasingly popular among C++ programmers due to its advantages Efficiency STL offers assortment of containers delegated to perform storage management which is tedious and prone to error Flexibility Users can use various algorithms with iterators regardless of the types of containers Ease of use STL containers and algorithms are intuitive and easy to apply Extensibility Users can add new containers and algorithms to STL 15

16 Containers STL has 7 basic containers divided into 2 types Sequential containers Represent sequences of elements accessed by positions (list) or indices (vector and deque) vector and deque overload the subscript operator [] Associative containers Represent collections of elements accessed by unique keys Type Container Description Sequential Associative list vector deque set multiset map multimap Bidirectional linked list of elements Array that grows and shrinks as needed Array with efficient insertions/deletions at either end Collection of nonduplicate keys A set with duplicates allowed Collection of nonduplicate elements accessed by keys A map with duplicates allowed 16

17 Sequential Container: Vector Basics on vectors A list that supports access to its elements by their indices Commonly, a vector can be instantiated without its size, because a vector grows and shrinks automatically Even instantiated with its size, a vector still grows automatically if required Operations Directly accessed by subscript operator [] Basic methods: size(), begin(), end(), insert(), erase() E.g.) vector<int> v; for (i = 0; i < 100; i++) v[i] = 1; v[70] = 3; v : v.begin() v[70] v.end() end() returns the iterator that points just beyond the end element 17

18 Accessing Elements with Iterators STL containers have associated iterator data types E.g., vector<int> has iterators with the following type vector<int>::iterator vector<int>::const_iterator Note that const_iterator is used if the iteration does not change any element A sequential container provides methods that return iterators that mark its beginning and end begin() returns the iterator that points the first element end() returns the iterator that points just beyond the last element Such methods allow us to loop safely without knowing how many elements happen to be in a container vector<int>::const_iterator it; it = v.begin(); // initializes iterator for vector v while (it!= v.end()) { // is the iterator at the end? cout << *it << endl; // prints the element pointed by it it++; // increments the iterator // *** iterators are handled just like pointers 18

19 Insertion into a Vector Suppose a vector v has n elements initially In operation v.insert(it, e), where it is an iterator pointing ith element, we need to make room for the new element by shifting forward the n - i elements (v[i],, v[n - 1]) Thus, the insert operation runs in O(n) time Note that insert at the end (it = v.end()) takes just O(1) time it v.end() v v n-1 i n i v.end() O(n) time means linear time directly propositional to n, O(1) time means constan time v e i n 19

20 Deletion from a Vector In operation v.erase(it), where it is an iterator pointing ith element, we need to fill the hole left by the removed element by shifting backward the n - i - 1 elements (v[i + 1],, v[n - 1]) The erase operation runs in O(n) time Note that erase at (n - 1)th index (i = n - 1) takes just O(1) time it v.end() v e i n-1 v i n-1 v.end() v i n-2 20

21 Example of Using a Vector Insertions and deletions at each end of a vector #include <iostream> #include <vector> using namespace std; void main() { vector<int> nums; nums.insert(nums.begin(), -999); // [ -999 ] nums.insert(nums.begin(), 14); // [ ] nums.insert(nums.end(), 57); // [ ] for(int i = 0; i < nums.size(); i++) cout << nums[i] << endl; // prints " " cout << endl; nums.erase(nums.begin()); nums.erase(nums.begin()); // 14 erased // -999 erased, 57 left for(int i = 0; i < nums.size(); i++) cout << nums[i] << endl; // prints "57" 21

22 Sequential Container: Deque N-1 A deque is almost the same as a vector If we replace vector with deque in the previous example, the output is exactly the same They differ in their underlying implementation, in particular with respect to insertions and deletions A vector generally requires O(n) time for insertions and deletions, but O(1) time for insertions and deletions at the end Efficient for applications in which insertions and deletions are typically done at the end A deque requires O(1) time for insertions and deletions at the beginning or at the end Thus, it is efficient for applications in which insertions and deletions are typically done at both ends Note that a deque takes more time than a vector for insertions and deletions at the end due to using a circular array mechanism Deque f r N-1 No shifting required for insertions and deletions at both ends, it maintains two pointers f and r for both ends in a circular fashion 22

23 Sequential Container: List The list container is a bidirectional node list Implemented as a doubly linked list Node implementation includes Reference to an element Link to the previous node Link to the next node Special trailer and header nodes Header points to the beginning Trailer points to the end prev elem next node header nodes trailer elements 23

24 l : l : Insertion into a List Visualization of l.insert(it, e), which takes O(1) time All we need to do is to move 4 links it a b c it a b c it e l : a b e c 24

25 Deletion from a List Visualization of l.remove(l.end()), which also takes O(1) time l : l : l.end() A B C D A B C X X D l : A B C 25

26 Example of Using a List #include <iostream> #include <string> #include <list> using namespace std; void dump(list<string>& l) { list<string>::const_iterator it; it = l.begin(); while (it!= l.end()) { cout << *it << endl; it++; // list iterator it // initialize it // is it at the end? // increment it void main() { list<string> names; names.insert(names.begin(), "Kamiko"); // [Kamiko] names.insert(names.end(), "Andre"); // [Kamiko Andre] names.insert(names.begin(), "Chengwen"); // [Chengwen Kamiko Andre] names.insert(names.begin(), "Maria"); // [Maris Chengwen...] dump(names); // prints "Maria Chengwen Kamiko Andre" names.reverse(); // reverse the list dump(names); // prints "Andre Kamiko Chengwen Maria" 26

27 Time Complexity of vectors, deques, and lists Operations vector deque list Insert/delete at the beginning Linear Constant Constant Insert/delete at the end Constant Constant Constant Insert/delete in the middle Linear Linear Constant Access the first element Constant Constant Constant Access the last element Constant Constant Constant Access the middle element Constant Constant Linear Linear = O(n), Constant = O(1) 27

28 Associative Containers The four basic associative containers in this chapter fall into the following two groups Sets A collection of zero or more nonduplicate, unordered keys E.g.) { jobs, gates, ellison A multiset is a set that allows duplicate keys E.g.) { jobs, gates, jobs, ellison, gates Maps A collection of zero or more nonduplicate, unordered (key, value) pairs Each pair has a nonduplicate key and a value associated with the key E.g.) { (jobs, apple), (gates, microsoft), (ellison, oracle) A multimap is a map that allows duplicate keys E.g.) { (jobs, apple), (gates, microsoft), (jobs, apple) 28

29 Sets The insert method of set class ensures that the set does not contain duplicate keys Without specified position s.insert(123); // insert somewhere of set s It can also be invoked in similar fashion to a vector s, s.insert(s.begin(), 66) // insert at the beginning of set s s.insert(s.end(), 99); // insert at the end of set s Unlike a vector, keys of a set do NOT ordered or accessed directly by index The set provides the find method It checks whether a set contains a specified key If so, it returns an iterator that marks the key Otherwise, returns an iterator that marks the end it = s.find(123); if (it == s.end()) throw string( key not found ); 29

30 Example of Using a Set #include <iostream> #include <set> using namespace std; void main() { set<int> s; s.insert(-999); s.insert(18); s.insert(321); s.insert(-999); // not inserted, duplicates not allowed set<int>::const_iterator it; it = s.begin(); while (it!= s.end()) cout << *it++ << endl; int key; cout << Enter an integer: "; cin >> key; it = s.find(key); if (it == s.end()) // if not found cout << key << " is not in set." << endl; else cout << key << " is in set." << endl; Prints -999, 18, 321 in some order 30

31 Maps A map is an association list, i.e., a list that associates a key with a value Thus, it is instantiated with two parameters key and value map<string, int> m1; map<int, float> m2; // string key, int value // int key, float value A map provides two ways to insert and access (key, value) pairs Like all other basic containers, it provides an insert method and as an associate container, it provides a find method In addition, it overloads subscript operator [] for both insertions and accesses m1[ one ] = 10; // == m1.insert( one, 10) m1[ two ] = 20; // == m1.insert( two, 20) m2[1] = 10.0; // == m2.insert(1, 10.0) m2[2] = 20.0; // == m2.insert(2, 20.0) cout >> m1[ one ] >> endl >> m2[1] >> endl; // prints 10 and

32 Example of Using a Map #include <iostream> #include <string> #include <map> using namespace std; void main() { map<string, int> m; m["zero"] = 0; m["one"] = 1; m["two"] = 2; m["three"] = 3; m["four"] = 4; m["five"] = 5; m["six"] = 6; m["seven"] = 7; m["eight"] = 8; m["nine"] = 9; cout << m["one"] << endl // prints 1 << m["three"] << endl // prints 3 << m["five"] << endl; // prints m["one"] = -1; // a duplicate pair cancels the previous association cout << m["one"] << endl; // prints -1 32

33 Container Adaptors Adapts a container to behave in a particular way Three basic container adaptors stack: creates LIFO (Last In First Out) list queue: creates FIFO (First In First Out) list priority_queue: creates a queue whose elements are removed in some priority (descending) order push top pop push push 1 rear top front front pop Stack Queue Priority queue top pop 33

34 stack Adaptor Adapts a deque container by default Definition stack<char> s; is equivalent to stack<char, deque<char>> s; We could force to adapt a vector stack<char, vector<char>> s; Methods push(e): inserts given element e into the stack pop(): removes the top element from the stack (returns void, normally follows top) top(): returns the top element of the stack without removing it empty(): returns whether the stack is empty or not (returns bool) 34

35 Example of Using stack (1/2) Reversing expression Original expression: (1 + 2) * 3 Output expression: 3*(2+1) buf (1 + 2) * 3 ) ( ( ) 3*(2+1) Output top 3 * ) ( Stack s 35

36 Example of Using stack (2/2) #include <iostream> #include <cctype> #include <stack> using namespace std; int main() { const string prompt = "Enter an algebraic expression: "; const char lparen = '('; const char rparen = ')'; stack<char> s; string buf; // read an algebraic expr. cout << prompt << endl; getline(cin, buf); // push chars into the stack for (int i=0; i<buf.length(); i++) if(!isspace(buf[i]) s.push(buf[i]); cout << "Original expression: " << buf << endl; // print reversed expr. cout << "Expression in reverse: "; // pop chars from the stack while (!s.empty()) { char t = s.top(); // get top s.pop(); // remove top if (t == lparen) t = rparen; else if (t == rparen) t = lparen; cout << t; cout << endl; return 0; 36

37 queue Adaptor Adapts a deque container by default Definition queue<int> q; is equivalent to queue<int, deque<int>> q; We could also force to adapt a vector queue<int, vector<int>> q; Methods push(e): inserts given element e into the queue pop(): removes the front element from the queue (returns void, normally follows front) front(): returns the front element of the queue without removing it empty(): returns whether the queue is empty or not (returns bool) 37

38 Example of Using queue #include <iostream> #include <queue> using namespace std; int main() { queue<int> q; // == queue<int, deque<int>> q.push(1); q.push(3); q.push(5); q.push(7); q.push(11); // pop and print until the queue is empty // output is while(!q.empty()) { cout << q.front() << endl; // returns an integer q.pop(); // returns void return 0; 38

39 priority_queue Adaptor Adapts a vector container by default Definition priority_queue<int> s; is equivalent to priority_queue<int, vector<int>> s; Ensures that a priority order is maintained during removals E.g., a priority_queue of integers might removes the integers in a descending order by value (i.e., large value first) Methods push(e): inserts given element e into the priority_queue pop(): removes the next priority element from the priority_queue (returns void, normally follows top) top(): returns the next priority element of the priority_queue without removing it empty(): returns whether the priority_queue is empty or not (returns bool) 39

40 Example of Using priority_queue #include <iostream> #include <functional> #include <cstdlib> #include <ctime> #include <queue> using namespace std; void main() { const int howmany = 8; int i; priority_queue<int> nums; srand(time(0)); // insert pseudo-random ints for (i = 0; i < howmany; i++) { int next = rand(); cout << next << endl; nums.push(next); // print ints in desc. order cout << \n*** Priority by value: << endl; for (i = 0; i < howmany; i++) { cout << nums.top() << endl; nums.pop(); *** Priority by value:

41 Other Containers The string class and the bitset class qualify as containers in the STL sense string class chars as string elements can be processed by STL iterators and algorithms such as find, for_each, random_shuffle Has the begin and end methods of the STL standard containers bitset class A bitset is a sequence of binary digits, e.g., Can be used to represent an integer in binary Has many methods to manipulate, evaluate and convert bits, e.g., invert, test, shift, and, or, xor, convert to int, Has overloaded [] to access individual bits with an index bitset<8> bs1; // bs1 = bitset<128> bs2; // bs2 = (128 0s) bitset<8> bs3(9); // bs3 = (= 9) if (bs3[0] == true)... ; // rightmost bit is indexed 0 41

42 Example of Using bitset #include <iostream> #include <bitset> using namespace std; const featurecount = 8; const unsigned Framed = 1; // const unsigned Bordered = 2; // const unsigned StdMenu = 4; // const unsigned ToolBar = 8; // const unsigned StatusBar = 16;// class Window { public: Window(const string& n, unsigned f) { name = n; features = bitset<featurecount> (f); createwindow(); Window(const char* n, unsigned f) { name = n; features = bitset<featurecount> (f); createwindow(); private: void createwindow() { cout << "\n*** Window features for << name << " given bit mask " if (features[0]) // 1st (rightmost) bit set? cout << "\t" << "framed" << endl; if (features[1]) // 2nd bit set? cout << "\t" << "bordered" << endl; if (features[2]) // 3rd bit set? cout << "\t << "with standard menu" << endl; if (features[3]) // 4th bit set? cout << "\t" << "with tool bar" << endl; if (features[4]) // 5th bit set? cout << "\t" << "with status bar" << endl; string name; bitset< featurecount > features; ; int main() { Window w1("w1", Framed ToolBar StatusBar); Window w2("w2", ToolBar Framed StatusBar); Window w3("w3", Framed StdMenu StatusBar ToolBar Bordered); return 0; << features << ":" << endl; 42

43 The Output of the bitset Example *** Window features for w1 given bit mask : framed with tool bar with status bar *** Window features for w2 given bit mask : framed with tool bar with status bar *** Window features for w3 given bit mask : framed bordered with standard menu with tool bar with status bar 43

44 STL Algorithms STL has rich assortment of algorithms for processing containers, which fall into some standard categories Sorting and searching Numerical processing Set operations Copying Algorithms are implemented as template functions STL containers are implemented as template classes STL algorithms processes a container by using iterators to traverse the container It does NOT require any container-specific information Works the same way on each container to be processed 44

45 Example of Manipulating a string with STL algorithms #include <iostream> #include <string> #include <algorithm> using namespace std; void printchar(char c) { cout << c; void main() { string s= Pele, the greatest ever"; cout << s: " << s << endl; cout << "s in reverse: "; for_each(s.rbegin(), s.rend(), printchar); // uses reverse iterators cout << endl; char* where = find(s.begin(), s.end(), 'a'); cout << 'a' is the << where - s.begin() + 1 << "th char in: " << s << endl; random_shuffle(s.begin(), s.end()); cout << "s after a random shuffle: " << s << endl; where = find(s.begin(), s.end(), 'a'); cout << "'a' is the << where - s.begin() + 1 << "th char in: " << s << endl; sort(s.begin(), s.end()); cout << "sorted in ascending order: " << s << endl; 45

46 reverse Algorithm The reverse algorithm uses iterators to put the container s elements in reverse order The prototype of reverse algorithm template<class BidirectionalIterator> // template header void reverse(bidirectionaliterator it1, // iterator 1 BidirectionalIterator it2); // iterator 2 With the BidirectionalIterator, the reverse algorithm can traverse a container either from beginning to end, or from end to beginning The reverse algorithm can not (or need not) distinguish between different containers, i.e., a vector and a deque 46

47 Example of Algorithms generate, replace_if, sort, and for_each // include other required headers... #include <algorithm> // for STL algorithm using namespace std; void dump(int i) { cout << i << endl; bool odd(int i) { return i % 2!= 0; bool comp(const int& i1, const int& i2) { return i1 > i2; // reverse comparator void main() { vector<int> v(10); // vector of 10 integers... // fill with random integers genearte(v.begin(), v.end(), rand); // replace odds with 0 replace_if(v.begin(), v.end(), odd, 0); // sort in descending order (ascending if comp is omitted) sort(v.begin(), v.end(), comp); // print all the integers in v for_each(v.begin(), v.end(), dump); 47

48 Output Stream Iterator A special STL iterator used to do output Instantiating an output iterator ostream_iterator<output_data_type> iterator_name(output_stream, separator) E.g.) ostream_iterator<char> oit(cout, " ") Instantiate an output iterator oit that outputs each char data to cout, which is separated by a blank // Outputs first 32th Fibonacci // numbers to a disk file and cout vector<int> fibs(32); fibs[0] = fibs[1] = 1; for (int i = 2; i < 32; i++) fibs[i] = fibs[i 1] + fibs[i-2]; ofstream outfile("output.dat"); ostream_iterator<int> outfileit(outfile, " "); ostream_iterator<int> stdoutit(cout, "\n"); copy(fibs.begin(), fibs.end(), outfileit); copy(fibs.begin(), fibs.end(), stdoutit); STL also provides input stream iterators for copying from input streams into variables or containers such as vectors and deques 48

49 Example of Algorithms nth_element, random_shuffle, and copy // include required headers... void main(){ const int len = 27; const int med = len / 2; // med = 13 char alph[] = "abcdefghijklmnopqrstuvwxyz{"; print("\n\noriginal array:\n", alph, len); // len(= 27) chars random_shuffle(alph, alph + len); print("\n\nafter random-shuffle:\n", alph, len); nth_element(alph, alph + med, alph + len); print("\n\nafter nth elemnet:\n", alph, len); print("\n\t < median: ", alph, med); print("\n\t median: ", alph + med, 1); print("\n\t > median: ", alph + med + 1, len / 2); cout << endl; void print(const char* msg, char a[], int len) { cout << msg; copy(a, a + len, ostream_iterator<char>(cout, " ")); Place the posth (= alph+med+1th) element in the position it would occupy if the sequence were sorted ascending and any element to the left of pos any element to the right of pos 49

50 The Output of the Previous Example Original array: a b c d e f g h i j k l m n o p q r s t u v w x y z { After random_shuffle: e t a r k m { l s y g q h o j x u z w p n b f d v c i After nth element: e i a c d f b h g j k l m n o p q r s t u v { w z x y < median: e i a c d f b h g j k l m median: n > median: o p q r s t u v { w z x y 50

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

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

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

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

More information

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC CMSC 341 Lecture 6 STL, Stacks, & Queues Based on slides by Lupoli, Dixon & Gibson at UMBC Templates 2 Common Uses for Templates Some common algorithms that easily lend themselves to templates: Swap what

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

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

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

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

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

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

CSCI-1200 Data Structures Fall 2016 Lecture 17 Associative Containers (Maps), Part 2

CSCI-1200 Data Structures Fall 2016 Lecture 17 Associative Containers (Maps), Part 2 CSCI-1200 Data Structures Fall 2016 Lecture 17 Associative Containers (Maps), Part 2 Review of Lecture 16 Maps are associations between keys and values. Maps have fast insert, access and remove 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

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

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

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible.

! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible. Exceptions! Exceptions are used to signal error or unexpected events that occur while a program is running.! An exception is a condition that occurs at execution time and makes normal continuation of the

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 6 Example Activity Diagram 1 Outline Chapter 6 Topics 6.6 C++ Standard Library Header Files 6.14 Inline Functions 6.16 Default Arguments 6.17 Unary Scope Resolution Operator

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

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

the Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue

the Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue the Queue 1 The Queue Abstract Data Type queue ADT using the STL queue 2 Simulating a Printer Queue designing the simulation simulation with STL queue 3 adapting STL list and vector using STL list as queue

More information

COMP322 - Introduction to C++

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

More information

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

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

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2 CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2 Review of Lecture 14 Maps are associations between keys and values. Maps have fast insert, access and remove operations:

More information

Containers in C++ and Java

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

More information

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47 Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers

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

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

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

Cpt S 122 Data Structures. Templates

Cpt S 122 Data Structures. Templates Cpt S 122 Data Structures Templates Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Function Template Function-template and function-template

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

Exercise 6.2 A generic container class

Exercise 6.2 A generic container class Exercise 6.2 A generic container class The goal of this exercise is to write a class Array that mimics the behavior of a C++ array, but provides more intelligent memory management a) Start with the input

More information

A linear structure is an ordered (e.g., sequenced) arrangement of elements.

A linear structure is an ordered (e.g., sequenced) arrangement of elements. Lists, Stacks, and Queues 1 A linear structure is an ordered (e.g., sequenced) arrangement of elements. There are three common types of linear structures: list stack queue random insertion and deletion

More information

Simulations. buffer of fixed capacity using the STL deque. modeling arrival times generating and processing jobs

Simulations. buffer of fixed capacity using the STL deque. modeling arrival times generating and processing jobs Simulations 1 Circular Queues buffer of fixed capacity using the STL deque 2 Simulating Waiting Lines using Queues modeling arrival times generating and processing jobs MCS 360 Lecture 18 Introduction

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

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

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

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

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011 CSCI 102L - Data Structures Midterm Exam #2 Spring 2011 (12:30pm - 1:50pm, Thursday, March 24) Instructor: Bill Cheng ( This exam is closed book, closed notes, closed everything. No cheat sheet allowed.

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

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

CSCI-1200 Data Structures Spring 2018 Lecture 15 Associative Containers (Maps), Part 2

CSCI-1200 Data Structures Spring 2018 Lecture 15 Associative Containers (Maps), Part 2 CSCI-1200 Data Structures Spring 2018 Lecture 15 Associative Containers (Maps), Part 2 Review of Lecture 14 Maps are associations between keys and values. Maps have fast insert, access and remove operations:

More information

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

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

More information

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

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50 Lists, Stacks, and Queues (Lists, Stacks, and Queues ) Data Structures and Programming Spring 2016 1 / 50 Abstract Data Types (ADT) Data type a set of objects + a set of operations Example: integer set

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

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

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

Chapter 18: Stacks And Queues

Chapter 18: Stacks And Queues Chapter 18: Stacks And Queues 18.1 Introduction to the Stack ADT Introduction to the Stack ADT Stack a LIFO (last in, first out) data structure Examples plates in a cafeteria return addresses for function

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

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

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

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

More information

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

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

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

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

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

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

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

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

Module 9. Templates & STL

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

More information

Function Templates. Consider the following function:

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

More information

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

Comp151. Generic Programming: Container Classes

Comp151. Generic Programming: Container Classes Comp151 Generic Programming: Container Classes Container Classes Container classes are a typical use for class templates, since we need container classes for objects of many different types, and the types

More information

Standard Library Reference

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

More information

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

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

More information

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

Lambda functions. Zoltán Porkoláb: C++11/14 1

Lambda functions. Zoltán Porkoláb: C++11/14 1 Lambda functions Terminology How it is compiled Capture by value and reference Mutable lambdas Use of this Init capture and generalized lambdas in C++14 Constexpr lambda and capture *this and C++17 Zoltán

More information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

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

CSC 222: Computer Programming II. Spring 2004

CSC 222: Computer Programming II. Spring 2004 CSC 222: Computer Programming II Spring 2004 Stacks and recursion stack ADT push, pop, top, empty, size vector-based implementation, library application: parenthesis/delimiter matching run-time

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

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

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

More information

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