You are on page 1of 23

Lecture 6

Standard Template Library

Computer Programming II



Function Template
Class Template
Standard Template Library (STL)
STL’s vector class
STL’s set class
STL’s map class

Computer Programming II


Computer Programming II 3 . class template) that accept any data type as parameters or attributes.Introduction Template allows us to write generic functions or classes (called function template. the compiler will produce a separate definition for every data type that uses the template. During compilation.

n = temp. 4 . we would need a different function: void Swap (string& s1. We can avoid writing the redundant code by replacing both functions with a function template. string& s2) { string temp = s1. m = n. } Computer Programming II These 2 functions do the same thing. s1 = s2.Function Template Recall the function to swap integers: void Swap (int& m. } To sort string. int& n) { int temp = m. s2 = temp. only different in the data type of objects they swap.

s2 = "Kelly".Function Template Template version of Swap() function: template <typename T> void Swap(T& x. Swap(s1. n = 66. // integers cout << "m = " << m << endl << "n = " << n << endl. one for string Output: m = 66 n = 22 s1 = Kelly s2 = Michael 5 . } Computer Programming II The symbol T is called type parameter. n). It is replaced by an actual type when the function is invoked. T& y) { T temp = x. s2). Compiler produces 2 definitions of Swap() functions: one for int. // strings cout << "s1 = " << s1 << endl << "s2 = " << s2 << endl. } int main() { int m = 22. Swap(m. x = y. string s1 = "Michael". return 0. y = temp.

typename V> Computer Programming II 6 . typename U. less confusing or template <class T> // old. A template may have several type parameters: template <typename T. except that it is preceded by the specification below: template <typename T> // new. confusing. class? and the type parameter T may be used in place of ordinary data types within the function definition.Declaring Function Template Function templates are declared in the same way as ordinary functions. The word typename/class here means any type.

A class template may have several type parameters. except that it is preceded by the specification below: template <typename T> class X { . }.. typename U> class X { .Declaring Class Template Class templates are declared the same way as ordinary class.. template <typename T.. Computer Programming II 7 . }..

Jackson) (P. } }.5). this->b = b.set ('P'. p1. p3. T b) { this->a = a. } Output: (3. "Jackson").set (3.print(). template <typename T> class Pair { T a.'J'). p3.Class Template Define a class template Pair that have 2 attributes of the same type. Pair<char> p3. p1. return 0. p2.print(). T b. Computer Programming II int main() { Pair<int> p1." << b << ")\n". } void print() const { cout << "(" << a << ".J) 8 .set ("Peter". p2.5) (Peter. Pair<string> p2.print(). public: void set (T a.

Pair<string> p2. Pair<char> p3.set (3. p3.J) 9 . T b. Computer Programming II int main() { Pair<int> p1. p1.print().set ('P'. return 0. } void print() const { cout << "(" << a << ".'J'). public: void set (T a.Class Template Class template allows us to write one class that works for many data types template <typename T> class Pair { T a. p2.5) (Peter. "Jackson").5)." << b << ")\n". p2.Jackson) (P. p3.print(). T b) { this->a = a. p1.print(). } Output: (3.set ("Peter". } }. this->b = b.

p2. Pair<int. U b) { this->a = a.Class Template : Multiple Type Parameters Class template that can have different types of attributes template <typename T.set (99.99) 10 .char> p1.string> p2. typename U> class Pair { T a.A) (B.set ('B'.99). } }.print().print(). p1. p3. this->b = b.print(). p2. Computer Programming II int main() { Pair<int." << b << ")\n"."Boy"). Pair<> p3. p3. 'A'). p1. } void print() const { cout << "(" << a << ". public: void set (T a.set (1. U b.Boy) (99. return 0. } Output: (1.

STL has very powerful features. Example: vector. set.Standard Template Library The Standard Template Library (STL) is part of the standard C++ library. STL has 3 basic components: Containers. etc Computer Programming II 11 . find. sort. list. Algorithms. map. Example: copy. Iterators Container: An STL container is a data structure or simply a collection of objects. etc Algorithm: An STL algorithm is a function for processing container’s contents.

STL Container Basics STL has 7 basic containers divided into 2 groups: •Sequential: access by index •Associative: access by key Container list Type Sequential Description Bidirectional linked list of elements vector * Sequential Array that grows and shrinks as needed deque Sequential Array with efficient insertions/deletions at either end set * Associative Collection of non-duplicate keys multiset Associative A set with duplicates allowed map * Collection of non-duplicate elements with access by key Associative multimap Associative A map with duplicates allowed * Covered in this lecture Computer Programming II 12 .

Common operations of STL's vector class: • push_back add an item to the end of the container • pop_back remove an item from the end of the container • operator[] return the item given a position • front return the first item in the container • back return the last item in the container • size return the size of the container • clear clear all the items in the container Computer Programming II 13 . Another advantage of vector is it provides random access to its elements.STL vector Class We can use the vector class as if it is an array that can be resized dynamically.

Output: 4 2 1 6 8 3 Push the item to the end of the vector The items are accessed just as if they are array elements 14 . v.push_back(4). } Computer Programming II Must specify the type of data to be stored. i < v.push_back(6). v.push_back(1).push_back(2). v. int main() { vector<int> v.STL vector Class Must include this #include <iostream> #include <vector> using namespace std.push_back(8). i++) cout << v[i] << " ". v. v. v.size().push_back(3). for (int i=0.

cin >> n.STL vector Class #include <iostream> #include <vector> using namespace std. Output: => 1 => 5 => 3 => 2 => -1 1 5 3 2 for (int i=0. int n. int main() { vector<int> v.push_back(n). we do not need to worry about memory allocating for it } while (n!=-1). With vector. if (n!=-1) v. Return the total number of elements in vector } Computer Programming II 15 . i < v.size(). return 0. i++) cout << v[i] << " ". do { cout << "=> ".

int main() { vector<int> v.size().push_back(4). v.STL vector Class #include <iostream> #include <vector> #include <algorithm> using namespace std. return 0.push_back(6). cout << "Vector elements unsorted:\n".push_back(2). v. i++) cout << v[i] << " ". sort (v. cout << "\nVector elements sorted:\n". v. i < v. v. for (int i = 0. for (int i = 0. i++) cout << v[i] << " ". vector elements can be sorted using STL algorithm sort function Vector elements unsorted: 4 2 7 6 Vector elements sorted: 2 4 6 7 } Computer Programming II 16 .begin().size(). i < v. v.end()).push_back(7).

i < nums.begin(). return 0.begin()+2). i++) cout << nums[i] << " ". // 14 -99 57 nums. // 14 22 -99 57 for (int i = 0.insert (nums. 57).insert (nums.end().erase (nums. 22).erase (nums.insert (nums.size().size(). // 14 22 57 nums.begin(). } Computer Programming II Insert -99 to the beginning of the vector Output: 14 22 -99 57 22 57 Insert 22 to as the 2nd element of the vector Erase the 3rd element in the vector 17 .insert (nums. #include <iostream> #include <vector> using namespace std. int main() { vector<int> nums. // 22 57 for (int i = 0. // -99 nums.begin()+1.STL vector Class A vector grows and shrinks automatically to meet its own storage needs. -99). cout << endl. nums. 14).begin()). // 14 -99 nums. nums. i < nums. i++) cout << nums[i] << endl.

Values = {Apple. map. "Cat" }  A map is a collection of (key. "Apple"). C}.4 Basic Associative Containers: set. Computer Programming II 18 . in each pair. the 2nd element is the value associated with the key. B. the set below contains 3 keys: { "Apple". ('B'. the map below contains 3 pairs: { ('A'. "Boy". For example. the 1st element is a non-duplicate key. multiset. ('C'. "Boy"). Cat}  multiset and multimap allow duplicate keys. and multimap  A set is a collection of non-duplicate sorted elements called keys. "Cat") } Keys = {A.  The 4 containers automatically sort the elements inserted.value) pairs sorted by the keys. For example. Boy.

Duplicates are ignored when inserted. Use find() method to look up a specified key in a set . key_type is the data types of the key. Use set when you want a sorted collection and you do not need random access to its elements. Use insert() method to insert an element into a set: set <int> s. set <key_type> s.insert (321).STL set Class A set is a collection of non-duplicate sorted elements called keys. Operator[] is not supported. Computer Programming II 19 . s. iterator is required to iterate/visit the elements in set.

STL Iterators Iterator: An STL iterator is a mechanism (pointer) for accessing the elements in a container one at a time. The type of iterator must match the type of container in order for the iterator to work.begin(). STL algorithms (find. set<int> s. Computer Programming II 20 . sort) etc) use iterators to process STL containers. Not all STL containers support the access to its elements via operator[]. for (set<int>::iterator it = s.end(). it++) cout << *it << " ". Iterator is useful in this case. it != s.

s.STL set Class #include <iostream> #include <set> using namespace std. s.insert (-999).end()) cout << *it++ << endl.find (target).insert (18). s. 21 . } Computer Programming II Output1: -999 18 321 Enter an integer: 5 5 is not in set. if (it == s.". Output2: -999 18 321 Enter an integer: 321 321 is IN set. // duplicate is ignored set<int>::iterator it = s.insert (321). it = s. Use iterator to iterate the set.insert (-999). // -999 18 321 int target. else cout << target << " is IN set. while (it != s. cout << "Enter an integer: ".begin().end()) // not found cout << target << " is NOT in set. cin >> target. return 0. s. int main() { set<int> s.".

except that in array the index is always int starting from 0. string> m. m['A'] = "Apple". m['A'] = "Angel". map cannot contain duplicates (multimap can). map is a bit similar to the array. map <key_type. // value associated to // key "A" is "Angel" // from here onwards Computer Programming II 22 . value_type> m. whereas in map the key can be of other data type.STL map Class A map is a collection of (key. map <char.value) pairs sorted by the keys. key_type and value_type are the data types of the key and the value respectively.

STL map Class #include <iostream> #include <map> using namespace std. it = m. m['C'] = "Cat". it++. return 0. } Computer Programming II char key. while (it != m. // insert m['A'] = "Apple". int main() { map <char.begin().". cout << "Enter a char: ". map <char. cout << m['A'] << " " // retrieve << m['B'] << " " << m['C'] << endl. m['B'] = "Boy". if (it == m.end()) { cout << it->first << " " << it->second << endl. string>::iterator it. string> m.find (key). else cout << key << " is IN map. } Output 1: Apple Boy Cat A Apple B Boy C Cat Enter a char: Z Z is NOT in map Output 2: Apple Boy Cat A Apple B Boy C Cat Enter a char: C C is IN map 23 . it = m.". cin >> key.end()) cout << key << " is NOT in map.