STANDARD TEMPLATE LIBRARY. Developed By Mrs. K.M.Sanghavi

Size: px
Start display at page:

Download "STANDARD TEMPLATE LIBRARY. Developed By Mrs. K.M.Sanghavi"

Transcription

1 STANDARD TEMPLATE LIBRARY Developed By Mrs. K.M.Sanghavi

2 STANDARD TEMPLATE LIBRARY Introduction to STL Components of STL : Containers, Algorithms, Iterator Containers : Sequence, Associative and Container Adapter(Derived) Algorithms- basic searching and sorting algorithms, min-max algorithm, set operations, heap sort, Iterators- input, output, forward, bidirectional and random access

3 STANDARD TEMPLATE LIBRARY (STL) Developed by Alexander Stepanov and Meng Lee of HP in Standard template library accepted in July 1994 into C++ ANSI Standard These are called as collection of General-purpose template classes( data structures) and functions 1

4 2 COMPONENTS OF STL Containers Algorithms Iterators

5 COMPONENTS OF STL Algorithms use iterators to interact with objects stored in containers Container Algorithm1 Algorithm 2 Object1 Object2 Iterator 1 Iterator 2 Object3 Iterator 3 Algorithm 3 3

6 CONTAINER Objects that hold data (of any data type) Example : Array Implemented by Template Classes 4

7 ALGORITHM These are procedures used to process the data contained in containers. Example : Searching, Sorting, Merging, Copying, Initializing Implemented by template functions 5

8 ITERATOR It is an object that points to an element in a container Used to move through the contents of container They can be incremented and decremented Connect Algorithms with Containers 6

9 7 COMPONENTS OF STL Containers

10 8 CATEGORIES OF CONTAINERS Sequence Containers Derived Containers : Container Adapters Associative Containers

11 CONTAINERS STL Defines 10 Containers 9

12 10 CATEGORIES OF CONTAINERS Sequence Associative Derived vector deque list set multiset map multimap stack queue Priority_queue

13 Common member functions for most STL Contaiers default constructor copy constructor destructor operator= operator== operator!= operator< operator<= operator> operator>= Constructs an empty container. Containers will have other constructors as well. Construct a copy of an already existing container of the same type. Clean up when container no longer needed. Assign one container to another. Test for equality, lexicographically. Test for inequality, lexicographically. Test for less than, lexicographically. Test for less than or equal to, lexicographically. Test for greater than, lexicographically. Test for greater than or equal to, lexicographically.

14 Commom member functions for most STL Contaiers empty max_size size swap insert erase clear begin end rbegin rend Test if container is empty. Return maximum number of components container can hold. Return number of elements container currently holds. Exchange all components with those of another container. Insert one or more components into a container. Erases one or more components from a container. Erases all components from a container. Return an iterator or const_iterator pointing to the first component. Return an iterator or const_iterator pointing to one-past-the-last component. Return a reverse_iterator or const_reverse_iterator pointing to the last component. Return a reverse_iterator or const_reverse_iterator pointing to one-before-the-first component.

15 Member functions found only in sequential STL containers assign Overwrite all components of current container. front Return a reference to a container's first component. back Return a reference to a container's last component. push_back Add a value to the end of a container. pop_back Remove the value at the end of a container. resize Change the size of a container, adding or removing values.

16 10 STL Container Header Files Sequence Associative Derived <vector > <deque> <list> set<set> multiset map multimap stack queue Priority_queue

17 SEQUENCE CONTAINERS Stores elements in a linear sequence Each element is related to other elements by its position along the line They allow insertion of elements Example Element 0 Element 1 Element 2.. Last element 11

18 THREE TYPES OF SEQUENCE CONTAINERS vector deque list 12

19 Vector : Sequence Container Expandable and dynamic array Grows and shrinks in size Insertion / Deletion of elements at back Permits direct access to any element 13

20 Vector : Sequence Container Container Header File Iterator vector <vector> Random Access 14

21 vector Sequence Container Declarations vector <type> v; type: int, float, etc. Iterators vector<type>::const_iterator itervar; const_iterator cannot modify elements vector<type>::reverse_iterator itervar; Visits elements in reverse order (end to beginning) Use rbegin to get starting point Use rend to get ending point 15

22 vector Sequence Container vector functions v.push_back(value) Add element to end (found in all sequence containers). v.size() Current size of vector v.capacity() How much vector can hold before reallocating Reallocation doubles size vector<type> v(a, a + SIZE) memory Creates vector v with elements from array a up to (not including) a + SIZE 16

23 vector Sequence Container vector functions v.insert(iterator, value ) Inserts value before location of iterator v.insert(iterator, array, array + SIZE) Inserts array elements (up to, but not including array + SIZE) into vector v.erase( iterator ) Remove element from container v.erase( iter1, iter2 ) Remove elements starting from iter1 and up to (not including) iter2 v.clear() Erases entire container 17

24 vector Sequence Container vector functions operations v.front(), v.back() Return first and last element v.[elementnumber] = value; Assign value to an element 18

25 Vector : Sequence Container int array[5] = {12, 7, 9, 21, 13 }; vector<int> v(array,array+5); v.pop_back(); v.push_back(15); v.begin(); v[3] 19

26 Vector : Sequence Container #include <vector> #include <iostream> using namespace std; void main { int arr[] = {12, 7, 9, 21, 13 }; // standard C array vector<int> v(arr, arr+5); // initialize vector with C array while ( { cout << } for(i=0; i<v.size(); ++i) cout<<v[i]<<' '; cout<<endl } ) // until vector is empty << ; // output last element of vector // delete the last element 20

27 O/P of previous program

28 Vector : Using Iterator #include <vector> #include <iostream> using namespace std; int main() { vector <int> vec1; vector <int>::iterator vec1_iter; vector <int>::reverse_iterator vec1_riter; vec1.push_back(10); vec1.push_back(7); vec1.push_back(3); 22

29 Vector : Using Iterator cout<<"vec1 data: "; for(int i=0; i<vec1.size(); ++i) cout<<vec1[i]<<' '; cout<<endl; cout<<"\noperation: vec1.begin()\n"; vec1_iter = vec1.begin(); cout<<"the first element of vec1 is "<<*vec1_iter<<endl; } cout<<"\noperation: vec1.rbegin()\n"; vec1_riter = vec1.rbegin(); cout<<"the first element of the reversed vec1 is ; cout<<*vec1_riter<<endl; return 0; 23

30 O/P of previous program vec1 data: Operation: vec1.begin() The first element of vec1 is10 Operation: vec1.rbegin() The first element of the reversed vec1 is : 3 24

31 Vector : Using Iterator #include <vector> #include <iostream> using namespace std; int main() { vector <int> vec1; vector <int>::reverse_iterator key; vec1.push_back(7); vec1.push_back(3); vec1.push_back(4); vec1.push_back(1); 25

32 Vector : Using Iterator cout<<"operation: vec1.rbegin() and vec1.rend()\n"; cout<<"vec1 data: "; for(key = vec1.rbegin(); key!= vec1.rend(); key++) cout<<*key<<' '; cout<<endl; return 0; } 26

33 O/P of previous program Operation: vec1.begin() and vec1.rend() vec1 data:

34 deque : Sequence Container Double ended Queue Insertion / Deletion of elements both ends Permits direct access to any element 28

35 deque : Sequence Container Container Header File Iterator deque <deque> Random Access 29

36 Deque #include <iostream> #include <deque> using namespace std; int main () { deque<int> mydeque; mydeque.push_back (100); mydeque.push_back (200); mydeque.push_back (300); cout << "\nthe final size of mydeque is " cout<<<< mydeque.size() << \n ; 30

37 Deque cout << "Popping out the elements in mydeque:"; while (!mydeque.empty()) { cout << mydeque.front(); mydeque.pop_front(); } cout << "\nthe final size of mydeque is " cout<<<< mydeque.size() << \n ; return 0; } 31

38 O/P of previous program The final size of mydeque is : 3 Popping out the elements in mydeque: The final size of mydeque is : 0 32

39 list : Sequence Container Bidirectional Insertion / Deletion of elements anywhwere 33

40 list : Sequence Container Container Header File Iterator list <list> Bidirectional 34

41 List #include <iostream.h> #include <list> void print(list <char> ); main() { list <char> l; list <char>::iterator p; l.push_back('o'); l.push_back('a'); l.push_back('t'); p=l.begin(); 35

42 List cout <<" "<< *p<<endl; // p refers to the 'o' in ('o', 'a', 't') print(l); l.insert(p, 'c'); // l is now ('c', 'o', 'a', 't') and p still refers to 'o cout <<" "<< *p<<endl; print(l); l.erase(p); cout <<" "<< *p<<endl; // p refers to an 'o' but it is not in l! print(l); 36

43 l.erase(l.begin()); //removes front of l print(l); } void print( list<char> a) { for(list<char>::iterator ai=a.begin(); ai!=a.end(); ++ai) cout << *ai << " "; cout << endl; cout << " "<<endl; } 37

44 O/P of previous program o o a t o c o a t null c a t a t 38

45 Comparison of sequence containers Container Random Access Insertion Deletion in middle Insertion or Deletion at the ends vector Fast Slow Fast at Back deque Fast Slow Fast at both ends list Slow Fast Fast at front 39

46 ASSOCIATIVE CONTAINERS Non-sequential Supports direct access to elements using keys The keys are typically numbers or strings 40

47 FOUR TYPES OF ASSOCIATIVE All these store data in a structure called tree which facilitates fast searching CONTAINERS multimap set Multiset map 41

48 Set & Multiset : Associative Container Stores a number of items which contain key Elements here are referenced by keys and not their positions. Example : Storing the objects of student class which are ordered alphabetically using names as keys Multiset allows duplicate items while set does not 42

49 Set #include <iostream> #include <string> #include <set> using namespace std; int main() { string a[] = {"Alice", "Bob", "Carl", "Dick", "Eve", "Fred } ; set<string> s(a, a+6); set<string>::iterator p = s.begin(); while (p!= s.end()) cout << *p++ << endl; cout<< <<endl; 43

50 Set set<string>::size_type numberdeleted = s.erase( Bob"); p = s.begin(); while (p!= s.end()) cout << *p++ << endl; cout<< <<endl; numberdeleted = s.erase( William"); p = s.begin(); while (p!= s.end()) cout << *p++ << endl; cout<< <<endl; s.erase(s.begin()); p = s.begin(); while (p!= s.end()) cout << *p++ << endl; cout<< <<endl; s.erase(s.find("carl"), s.find( Eve")); p = s.begin(); while (p!= s.end()) cout << *p++ << endl; 44

51 Set cout<< <<endl; s.clear(); if (s.empty()) cout << "\nthe set is now empty."; } 45

52 O/P of previous program Alice Bob Carl Dick Eve Fred Alice Carl Dick Eve Fred 46

53 O/P of previous program Alice Carl Dick Eve Fred Carl Dick Eve Fred 47

54 O/P of previous program Fred The set is now empty. 48

55 MultiSet #include <iostream> #include <string> #include <set> class Book { public : Book() { title = author = publisher = date = ""; } Book(string a) { author = a; title = publisher = date = ""; } 49

56 MultiSet Book(string t, string a, string p, string d) { title = t; author = a; publisher = p; date = d; } string Author() { return author; } 50

57 MultiSet void GetInfo(string &t, string &a, string &p, string &d) { t = title; a = author; p = publisher; d = date; } private: string author; string title; string publisher; string date; }; 51

58 Multiset int main() { multiset<book> b; string a; b.insert(book("c++ book", ABC", McGraw-Hill", "1998")); b.insert(book( Java ", XYZ", BB Publisher", 2001")); b.insert(book( Let Us C", Kanetkar", McGraw-Hill ", "1997")); multiset<book>::iterator p = b.begin(); while (p!= booklist.end()) { cout<<*p++<<endl; } }; 52

59 O/P of previous program C++ book ABC McGraw-Hill 1998 Java XYZ BB Publisher 2001 Let Us C Kanetkar McGraw-Hill

60 Map & Multimap : Associative Container Stores pair of items, one called key and other value Manipulate the values using the keys associated with them Values are called as mapped values Multimap allows multiple keys while map does not 24

61 Map #include <map> #include <algorithm> #include <iostream> #include <string> int main() { map<string,int> amap; amap[ First ]=1; amap[ Second ]=2; cout << "Size : " << amap.size() << endl; amap["third"]=3; amap[ Fourth"]=4; cout << "Size : " << amap.size() << endl; 61 71

62 Map map<string,int>::iterator it; for ( it=amap.begin(); it!=amap.end(); it++) cout << "map : " << it->first << " " << it->second << endl; cout << amap.find("third")->second << endl; return 0; } 62 71

63 THREE TYPES OF DERIVED CONTAINERS These are known as container adaptors stack priority_queue queue 25

64 Stack, Queue, Priority_Queue #include <stack> #include <queue> using namespace std; int main() { // STL Stack stack<int, vector<int> > S; // Changing default container for ( int i=0 ; i<10; i++ ) S.push(i); for ( int i=0 ; i<10; i++ ) { cout << S.top() << " "; S.top() = 2 * S.top(); cout << S.top() << endl; S.pop(); }

65 // STL Queue queue<int> Q; for ( int i=0 ; i<10; i++ ) Q.push(i); for ( int i=0 ; i<10; i++ ) { cout << Q.front() << endl; Q.pop(); }

66 // STL Priority Queue priority_queue<int> P; for ( int i=0 ; i<10; i++ ) P.push(i); for ( int i=0 ; i<10; i++ ) { cout << P.top() << endl; P.pop(); } }

67 Stack, Queue, Priority_Queue : Derived Containers Can be created from different sequence containers These do not support Iterators Therefore cannot be used for data manipulation Support two member functions : push( ) and pop( ) 26

68 COMPONENTS OF STL Containers Algorithms Iterators 27

69 2. ALGORITMS Generic functions that handle common tasks such as searching, sorting, comparing, and editing More than 60 Algortihms exist These are not member functions or friends of containers but are standalone template functions To use them we include<algorithm> in the program 28

70 CATEGORY OF ALGORITHMS Retrieve or nonmutating(non mdifying) Relational Mutating (Modifying) Set Sorting 29

71 Non-Mutating Algorithms Operations Description adjacent_find() Find equal adjacent elements in range count() count_if equal() find() Count appearances of value in range Return number of elements in range satisfying condition Test whether the elements in two ranges are equal Find value in range 30

72 Non-Mutating Algorithms Operations find_end find_first_of() find_if() for_each() mismatch() Description Find last subsequence in range Find element from set in range Find element in range Apply function to range Return first position where two ranges differ 31

73 Non-Mutating Algorithms Operations search() search_n() Description Search range for subsequence Search range of elements 32

74 Mutating Algorithms Copy() Copy range of elements (function template ) copy_n() Copy elements (function template ) copy_if ()Copy certain elements of range (function template ) copy_backward( )Copy range of elements backward (function template ) move() Move range of elements (function template ) move_backward() Move range of elements 17 backward (function template ) 33

75 Mutating Algorithms swapexchange values of two objects (function template ) swap_ranges Exchange values of two ranges (function template ) iter_swapexchange values of objects pointed by two iterators (function template ) transformtransform range (function template ) replacereplace value in range (function template ) Replace_if() replace values in range (function template ) Replace_copy() Copy range 34

76 Mutating Algorithms fill() Fill range with value (function template ) fill_n() Fill sequence with value (function template ) generate ( ) Generate values for range with function (function template ) Generate_ n( ) Generate values for sequence with function (function template ) 35

77 Mutating Algorithms remove Remove value from range (function template ) remove_if()remove elements from range (function template ) remove_copy()copy range removing value (function template ) remove_copy_if()copy range removing values (function template ) unique Remove consecutive duplicates in range (function template ) 36

78 Mutating Algorithms Unique_copy()Copy range removing duplicates (function template ) Reverse( ) Reverse range (function template ) reverse_copycopy range reversed (function template ) rotate()rotate left the elements in range (function template ) 37

79 Mutating Algorithms rotate_copycopy range rotated left (function template ) random_shufflerandomly rearrange elements in range (function template ) shuffle Randomly rearrange elements in range using generator (function template ) 38

80 Algorithms #include<algorithm> #include<iostream> using namespace std; int main() { vector<int> v; vector<int>p; v.push_back(10); v.push_back(20); p.push_back(60); v.push_back(40); v.push_back(10); v.push_back(50); swap(v,p); }

81 Algorithms int n, value,arr[10],i; int *Limit = arr + n; cout<< Enter the numbers ; for(i =0; i< n;++i) { cin>>value; arr[i] = value; } sort(arr, Limit);

82 Algorithms cout<< Sorted List is ; for(i =0; i< n;++i) { cout<<arr[i]; cout<<endl; } return 0; }

83 Algorithm Searching Example find, search, binary search / binary_search example #include <iostream> // std::cout #include <algorithm> // std::binary_search, std::sort #include <vector> // std::vector bool myfunction (int i,int j) { return (i<j); } int main () { int myints[] = {1,2,3,4,5,4,3,2,1}; int my2ints[] = {5,4,3,2}; vector<int> v(myints,myints+9); // vector<int>::iterator it;

84 Algorithm Searching Example find, search, binary search // using default comparison: sort (v.begin(), v.end()); it = find(v.begin(), v.end(), 3); cout<< Item found at position <<(it-v.begin()); it = search (v.begin(), v.end(), my2ints, my2ints+4); cout<< Item found at position <<(it-v.begin());

85 Algorithm Searching Example find, search, binary search cout << "looking for a 3... "; if (binary_search (v.begin(), v.end(), 3)) cout << "found!\n"; else std::cout << "not found.\n"; // using myfunction as comp: sort (v.begin(), v.end(), myfunction); cout << "looking for a 6... "; if (binary_search (v.begin(), v.end(), 6, myfunction)) std::cout << "found!\n"; else std::cout << "not found.\n"; } return 0; Output: looking for a 3... found! looking for a 6... not found.

86 Algorithm Min Max Example / min max example #include <iostream> #include <algorithm> // std::cout int main () { cout<< \n min(20,10) = <<min(20,10); cout<< \n min( a, b) <<min( a, b ); cout<< \n max( e, f ) = <<max( e, f ); }

87 Algorithm Set Union Example #include <iostream> // std::cout #include <algorithm> #include <vector> // std::vector int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; vector<int> v(10); // vector<int>::iterator it; std::sort (first,first+5); // std::sort (second,second+5); //

88 Algorithm Set OperationsExample it= set_union (first, first+5, second, second+5, v.begin()); // v.resize(it-v.begin()); // cout << "The union has " << (v.size()) << " elements:\n"; for (it=v.begin(); it!=v.end(); ++it) cout << ' ' << *it; cout << '\n'; return 0; } Output: The union has 8 elements:

89 Algorithm Set Intersection Example #include <iostream> // std::cout #include <algorithm> #include <vector> // std::vector int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; vector<int> v(10); // vector<int>::iterator it; std::sort (first,first+5); // std::sort (second,second+5); //

90 Algorithm Set Intersection Example it= set_intersection (first, first+5, second, second+5, v.begin()); // v.resize(it-v.begin()); // cout << "The intersection has has " << (v.size()) << " elements:\n"; for (it=v.begin(); it!=v.end(); ++it) cout << ' ' << *it; cout << '\n'; return 0; } Output: The intersection has 2 elements: {10 20}

91 Algorithm Set difference Example it= set_difference (first, first+5, second, second+5, v.begin()); // v.resize(it-v.begin()); // cout << "The intersection has has " << (v.size()) << " elements:\n"; for (it=v.begin(); it!=v.end(); ++it) cout << ' ' << *it; cout << '\n'; return 0; } Output: The difference has 3 elements: { }

92 Iterators input output forward bidirectional random access 39

93 Input & Output Iterator Provides least functions Used only to traverse in a container 40

94 Forward Iterator Supports all functions of input & output iterators Retain its position in the container 41

95 Bi-directional Iterator Supports all functions of forward iterators Provides ability to move in backward direction in the container 42

96 Random Access Iterator Supports all functions of bidirectional iterators Has the ability to jump to any arbirtary location 43

97 Iterators and their characteristics Iterator Access Method Direction of Movement I/O Capability Input Linear Forward Read Output Linear Forward Write Forward Linear Forward Read/Write Bidirectional Linear Forward & Backward Read/Write Random Access Random Forward & Backward Read/Write 44

98 Operations Supported by Iterators Iterator Elemen t Access Read Write Increme nt Compari son Input v=*p ++ ==,!= Output *p=v ++ Forward v=*p *p=v ++ ==,!= Bidirection al Random Access & [ ] v=*p *p=v ++,-- ==,!= v=*p *p=v ++,--,+,- ==,!=,<,>, <=,>= 45

99 Iterator vector<int> array_ size_ 4 vector<int>::iterator The iterator corresponding to the class vector<int> is of the type vector<int>::iterator 46

100 Iterator The member functions begin() and end() return an iterator to the first and past the last element of a container vector<int> v array_ v.begin() v.end() size_ 4 47

101 Iterator One can have multiple iterators pointing to different or identical elements in the container vector<int> v array_ size_ 4 i1 i2 i3 48

102 Istream & ostream iterator Input & output iterator Example // istream_iterator example #include <iostream> // std::cin, std::cout #include <iterator> // std::istream_iterator int main () { double value1, value2; std::cout << "Please, insert two values: "; std::istream_iterator<double> iit (std::cin); // stdin iterator std::ostream_iterator<int> ot(std cout, ); value1=*iit; ++iit; value2=*iit; std::cout << value1 << "*" << value2 << "=" << (value1*value2) << '\n'; return 0; }

103 Inserter Example #include <iostream> // std::cout #include <iterator> // std::front_inserter #include <list> // std::list #include <algorithm> // std::copy int main () { list<int> l1, l2; for (int i=1; i<=5; i++) { l1.push_back(i); l2.push_back(i*10); }

104 Inserter Example Continued list<int>::iterator it = l1.begin(); advance (it,3); copy (l2.begin(), l2.end(), inserter(l1,it)); std::cout << l1 contains:"; for ( it = l1.begin(); it!= l1.end(); ++it ) cout << ' ' << *it; std::cout << '\n'; return 0; } Output

105 Vector #include<vector> #include<iostream> using namespace std; void display( vector<int> &v) { for(int i=0;i<v.size();i++) cout<<v[i]<< ; cout<< \n ; } 49

106 Vector int main() { vector<int> v; //Create vector of type int cout<<"initial size = " <<v.size()<<"\n"; int x; cout<< Enter Five values ; for(i=0;i<5;i++) { cin>>x; v.push_back(x); //Putting values into vector } 50

107 Vector cout<< Size after adding 5 values : <<v.size() << \n ; display(v); //Display current contents ; v.push_back(6.6); //float value truncated to int vector<int> :: iterator itr = v.begin(); itr = itr + 3; //Iterator display(v); v,.erase(v.begin() +3, v.begin( )+5); display(v); 51

108 Vector Constructors of Vector : vector <int> v; vector<int> v(10); vector<int> v1(v); // 0 length vector // 10-element int vector //Creates v1 from v vector<int> v(5,2); // 5-element vector of 2s or vector<char>v(25, A ); //25-element vector each // initialized with A 52

109 Functions of vector Function Name at ( ) Description Returns the value of the element located at element in the vector. Example: x = vect.at(5); The statement above assigns the value of the 5 th element of vect to x. 53

110 Functions of vector Function Name back() Description Returns the value of the element located at end element in the vector. Example: x = vect.back(); The statement above assigns the value of the last element of vect to x. 54

111 Functions of vector Function Name capacity( ) Description Returns the maximum number of elements that may be stored in the vector without additional memory being allocated. (This is not the same value as returned by the size member function). Example: x = vect.capacity(); The statement above assigns the capacity of vect to x. 55

112 Functions of vector Function Name clear( ) Description Clears a vector of all its elements. Example: vect.clear(); The statement above removes all the elements from vect. 56

113 Functions of vector Function Name empty( ) Description Returns true if the vector is empty. Otherwise, it returns false. Example: if (vect.empty()) cout << "The vector is empty."; The statement above displays the message if vect is empty. 57

114 Functions of vector Function Name pop_back() Description Removes the last element from the vector. Example: vect.pop_back(); The statement above removes the last element of vect, thus reducing its size by 1. 58

115 Functions of vector Function Name push_back(va lue) Description Stores a value in the last element of the vector. If the vector is full or empty, a new element is created. Example: vect.push_back(7); The statement above stores 7 in the last element of vect. 59

116 Functions of vector Function Name reverse() Description Reverses the order of the elements in the vector (the last element becomes the first element, and the first element becomes the last element.) Example: vect.reverse(); The statement above reverses the order of the element in vect. 60

117 Functions of vector Function Name resize(eleme nts, value) Description Resizes a vector by elements elements. Each of the new elements is initialized with the value in value. Example: vect.resize(5, 1); The statement above increases the size of vect by 5 elements. The 5 new elements are initialized to the value 1. 61

118 Functions of vector Function Name swap(vector2 ) Description Swaps the contents of the vector with the contents of vector2. Example: vect1.swap(vect2); The statement above swaps the contents of vect1 and vect2. 62

119 Functions of vector Function Name erase(srcpos, destpos) Description Erases the contents of the vector from Source position to Destination position Example: vect1.erase(1,5); The statement above erases the contents of vect1 from position 1 to 5. 63

120 List #include<list> #include<iostream> #include<cstdlib> //For rand( ) using namespace std; void display( list<int> &l) { list<int> ::iterator p; for(p= l.begin() ;p!= l.end(); ++p) cout<<*p<< ; cout<< \n ; } 65

121 list int main() { list<int> list1; //Empty list of 0 length list<int> list2(5); // Empty list of capacity 5 for(i=0;i<3;i++) list1.push_back(rand( )/100 ); list<int>::iterator p; for(p=list2.begin(); p!= list2.end();++p) *p = rand( ) /100; 66

122 list cout<< List1 : << \n ; display(list1); cout<< List2 : << \n ; display(list2); list1.push_front(100); list1.push_back(200); list2.pop_front( ) ; display(list1); display(list2); 67

123 list list<int> lista, listb; lista = list1; listb = list2; list1.merge(list2); cout<< List1 : << \n ; display(list1); lista.sort( ); listb.sort( ); lista.merge( listb) ; 68

124 list cout<< Merged Sorted List : << \n ; display(lista); lista.reverse( ); cout<< Reversed Merged List : << \n ; display(lista); return(0); } 68

125 Procedures on Heap Heapify Build Heap Heap Sort

126 Heapify Heapify picks the largest child key and compare it to the parent key. If parent key is larger than heapify quits, otherwise it swaps the parent key with the largest child key. So that the parent is now becomes larger than its children. { Heapify(A, i) } l left(i) r right(i) if l <= heapsize[a] and A[l] > A[i] then largest l else largest i if r <= heapsize[a] and A[r] > A[largest] then largest r if largest!= i then swap A[i] A[largest] Heapify(A, largest)

127 BUILD HEAP We can use the procedure 'Heapify' in a bottom-up fashion to convert an array A[1.. n] into a heap. Since the elements in the subarray A[n/ n] are all leaves, the procedure BUILD_HEAP goes through the remaining nodes of the tree and runs 'Heapify' on each one. The bottom-up order of processing node guarantees that the subtree rooted at children are heap before 'Heapify' is run at their parent. { Buildheap(A) } heapsize[a] length[a] for i length[a]/2 //down to 1 do Heapify(A, i)

128 Heap Sort Algorithm The heap sort algorithm starts by using procedure BUILD-HEAP to build a heap on the input array A[1.. n]. Since the maximum element of the array stored at the root A[1], it can be put into its correct final position by exchanging it with A[n] (the last element in A). If we now discard node n from the heap than the remaining elements can be made into heap. Note that the new element at the root may violate the heap property. All that is needed to restore the heap property. Heapsort(A) { } Buildheap(A) for i length[a] //down to 2 do swap A[1] A[i] heapsize[a] heapsize[a] - 1 Heapify(A, 1)

129 Example: Convert the following array to a heap Picture the array as a complete binary tree:

130 swap swap swap

131 Heap Sort The heapsort algorithm consists of two phases: - build a heap from an arbitrary array - use the heap to sort the data To sort the elements in the decreasing order, use a min heap To sort the elements in the increasing order, use a max heap

132 Example of Heap Sort Take out biggest Move the last element to the root Array A Sorted:

133 HEAPIFY() swap 1 4 Array A Sorted:

134 Array A Sorted:

135 Move the last element to the root 12 7 Take out biggest Array A Sorted:

136 Array A Sorted:

137 HEAPIFY() swap Array A Sorted:

138 Array A Sorted:

139 Take out biggest 12 Move the last element to the root Array A Sorted:

140 1 swap 4 7 Array A Sorted:

141 7 4 1 Array A Sorted:

142 4 1 Take out biggest Move the last element to the root 7 Array A Sorted:

143 HEAPIFY() swap 1 4 Array A Sorted:

144 Move the last element to the root 1 Take out biggest 4 Array A Sorted:

145 1 Take out biggest Array A Sorted:

146 Sorted:

147 Heap Sort using STL #include <iostream> #include <algorithm> #include <vector> Output: Vector contains : int main () { int array[] = {10,20,30,5,15,25,36}; vector<int> v(array, array+7); cout<< \nthe Vector contains : for(int i=0;i<v.size();i++) { cout<< <<v[i] ; }

148 Heap Sort using STL cout<< \n Heapify ; make_heap (v.begin(),v.end()); cout << "initial max heap : " << v.front() << \n ; cout<< \nthe Vector contains after heapifying : for(int i=0;i<v.size();i++) { cout<< <<v[i] ; } Output: Heapify initial max heap :36 The Vector contains after heapifying:

149 Heap Sort using STL sort_heap(v.begin( ),v.end()); pop_heap (v.begin(),v.end()); v.pop_back(); cout << "max heap after pop : " << v.front() << '\n'; Output: max heap after pop:36

150 Heap Sort using STL v.push_back(99); push_heap (v.begin(),v.end()); std::cout << "max heap after push: " << v.front() << '\n'; Output: max heap after pop:99

151 sort_heap (v.begin(),v.end()); std::cout << "final sorted range :"; for (unsigned i=0; i<v.size(); i++) std::cout << ' ' << v[i]; std::cout << '\n'; return 0; }

152 Container Adaptors Container classes implemented on top of the existing containers (adapt their interface) stack (default container: deque) queue (default container: deque) priority_queue (default container: vector) Can change underlying container class stack<int, vector<int> > Note, need space in between >

153 Operations on Adapter Containers Descr. Method S Q P # of elements (E) size is empty? empty E at top (ref) top Add E top / back push Del E top / front pop E at front (ref) front E at back (ref) back - + -

154 Common Operations on Associative Containers Descr. Method S M # of elements (E) size + + is empty? empty + + Add element insert + + Delete element erase + + Find element (ref) find + + The same == + + Subscript with key [] + +

/ 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

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

Standard Template Library

Standard Template Library Standard Template Library Wednesday, October 10, 2007 10:09 AM 9.3 "Quick Peek" STL history 1990s Alex Stepanov & Meng Lee of HP Labs 1994 ANSI/IS0 standard Components Container class templates Iterators

More information

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

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

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

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 Standard Template Library Classes

The Standard Template Library Classes The Standard Template Library Classes Lecture 33 Sections 9.7, 9.8 Robb T. Koether Hampden-Sydney College Wed, Apr 23, 2014 Robb T. Koether (Hampden-Sydney College) The Standard Template Library Classes

More information

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

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

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

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort?

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort? So far we have studied: Comparisons Insertion Sort Merge Sort Worst case Θ(n 2 ) Θ(nlgn) Best case Θ(n) Θ(nlgn) Sorting Revisited So far we talked about two algorithms to sort an array of numbers What

More information

Comparisons. Heaps. Heaps. Heaps. Sorting Revisited. Heaps. So far we talked about two algorithms to sort an array of numbers

Comparisons. Heaps. Heaps. Heaps. Sorting Revisited. Heaps. So far we talked about two algorithms to sort an array of numbers So far we have studied: Comparisons Tree is completely filled on all levels except possibly the lowest, which is filled from the left up to a point Insertion Sort Merge Sort Worst case Θ(n ) Θ(nlgn) Best

More information

Unit 4 Basic Collections

Unit 4 Basic Collections Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program

More information

STL Quick Reference for CS 241

STL Quick Reference for CS 241 STL Quick Reference for CS 241 Spring 2018 The purpose of this document is to provide basic information on those elements of the C++14 standard library we think are most likely to be needed in CS 241.

More information

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

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

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

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

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

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

Major Language Changes, pt. 1

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

More information

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

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

The Heap Data Structure

The Heap Data Structure The Heap Data Structure Def: A heap is a nearly complete binary tree with the following two properties: Structural property: all levels are full, except possibly the last one, which is filled from left

More information

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

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

More information

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

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types Arrays - Vectors Data Types Data Type: I. set of values II. set of operations over those values Example: Integer I. whole numbers, -32768 to 32767 II. +, -, *, /, %, ==,!=, , =,... Which operation

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

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

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

C++ Standard Template Library. Contents. Pierre Fierz. 1 Introduction. 2 Organization of STL Header Files. Organization of STL Header Files Contents Chapter 3 1 Lecture Advanced C++ 05.03.2012 2 3 4 Associative 5 Associative 6 Bernese University of Applied Sciences School of Engineering and Information Technology Division of Computer Science

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

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

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

Abstract Data Types 1

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

More information

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

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

More information

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

CS60020: Foundations of Algorithm Design and Machine Learning. Sourangshu Bhattacharya

CS60020: Foundations of Algorithm Design and Machine Learning. Sourangshu Bhattacharya CS60020: Foundations of Algorithm Design and Machine Learning Sourangshu Bhattacharya Special Types of Trees Def: Full binary tree = a binary tree in which each node is either a leaf or has degree exactly

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

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

MODULE 35 --THE STL-- ALGORITHM PART III

MODULE 35 --THE STL-- ALGORITHM PART III MODULE 35 --THE STL-- ALGORITHM PART III My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation example is given at the end of this

More information

GridKa School 2013: Effective Analysis C++ Standard Template Library

GridKa School 2013: Effective Analysis C++ Standard Template Library GridKa School 2013: Effective Analysis C++ Standard Template Library Introduction Jörg Meyer, Steinbuch Centre for Computing, Scientific Data Management KIT University of the State of Baden-Wuerttemberg

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

Priority Queues and Huffman Trees

Priority Queues and Huffman Trees Priority Queues and Huffman Trees 1 the Heap storing the heap with a vector deleting from the heap 2 Binary Search Trees sorting integer numbers deleting from a binary search tree 3 Huffman Trees encoding

More information

To know the relationships among containers, iterators, and algorithms ( 22.2).

To know the relationships among containers, iterators, and algorithms ( 22.2). CHAPTER 22 STL Containers Objectives To know the relationships among containers, iterators, and algorithms ( 22.2). To distinguish sequence containers, associative containers, and container adapters (

More information

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

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

MODULE 37 --THE STL-- ALGORITHM PART V

MODULE 37 --THE STL-- ALGORITHM PART V MODULE 37 --THE STL-- ALGORITHM PART V My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation example is given at the end of this

More information

MODULE 33 --THE STL-- ALGORITHM PART I

MODULE 33 --THE STL-- ALGORITHM PART I MODULE 33 --THE STL-- ALGORITHM PART I My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation examples given at the end of this Module.

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

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

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

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

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

403: Algorithms and Data Structures. Heaps. Fall 2016 UAlbany Computer Science. Some slides borrowed by David Luebke

403: Algorithms and Data Structures. Heaps. Fall 2016 UAlbany Computer Science. Some slides borrowed by David Luebke 403: Algorithms and Data Structures Heaps Fall 20 UAlbany Computer Science Some slides borrowed by David Luebke Birdseye view plan For the next several lectures we will be looking at sorting and related

More information

Topic: Heaps and priority queues

Topic: Heaps and priority queues David Keil Data Structures 8/05 1 Topic: Heaps and priority queues The priority-queue problem The heap solution Binary trees and complete binary trees Running time of heap operations Array implementation

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

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

Heapsort. Heap data structure

Heapsort. Heap data structure Heapsort Heap data structure. Heap A (not garbage-collected storage) is a nearly complete binary tree.. Height of node = # of edges on a longest simple path from the node down to a leaf.. Height of heap

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

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

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

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

More information

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

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

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 An important part of every container is the type of iterator it supports. This determines which algorithms can be applied to the container. A vector supports random-access iterators i.e., all iterator

More information

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

Computer Application and Practice 2: Templates and the Standard Template Library Computer Application and Practice 2: Templates and the Standard Template Library 2014 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Basics on templates Template classes Template

More information

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

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

More information

COMP Data Structures

COMP Data Structures COMP 2140 - Data Structures Shahin Kamali Topic 5 - Sorting University of Manitoba Based on notes by S. Durocher. COMP 2140 - Data Structures 1 / 55 Overview Review: Insertion Sort Merge Sort Quicksort

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

Standard Template Library. Outline

Standard Template Library. Outline C++ Standard Template Library Spring 2015 Yanjun Li CS2200 1 Outline Standard Template Library Containers & Iterators STL vector STL list STL stack STL queue Fall 2008 Yanjun Li CS2200 2 Software Engineering

More information

Heapsort. Algorithms.

Heapsort. Algorithms. Heapsort Algorithms www.srijon.softallybd.com Outline Heaps Maintaining the heap property Building a heap The heapsort algorithm Priority queues 2 The purpose of this chapter In this chapter, we introduce

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

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

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

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

Chapter 6 Heap and Its Application

Chapter 6 Heap and Its Application Chapter 6 Heap and Its Application We have already discussed two sorting algorithms: Insertion sort and Merge sort; and also witnessed both Bubble sort and Selection sort in a project. Insertion sort takes

More information

Introduction to Algorithms 3 rd edition

Introduction to Algorithms 3 rd edition Introduction to Algorithms 3 rd edition Heapsort Mohammad Heidari Faculty of Mathematics and Computer Khansar March 6, 2017 M.Heidari (Computer Science Khansar) Introduction to Algorithms March 6, 2017

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

Basic Data Structures and Heaps

Basic Data Structures and Heaps Basic Data Structures and Heaps David Kauchak Sorting demo (http://math.hws.edu/tmcm/java/xsortlab/) Data structures What is a data structure? Way of storing data that facilitates particular operations.

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

Cours de C++ Introduction

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

More information

Lecture 5: Sorting Part A

Lecture 5: Sorting Part A Lecture 5: Sorting Part A Heapsort Running time O(n lg n), like merge sort Sorts in place (as insertion sort), only constant number of array elements are stored outside the input array at any time Combines

More information

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

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

More information

C++ Standard Template Library

C++ Standard Template Library C++ Standard Template Library CS 247: Software Engineering Principles Generic Algorithms A collection of useful, typesafe, generic (i.e., type-parameterized) containers that - know (almost) nothing about

More information

Lectures 11,12. Online documentation & links

Lectures 11,12. Online documentation & links Lectures 11,12 1. Quicksort algorithm 2. Mergesort algorithm 3. Big O notation 4. Estimating computational efficiency of binary search, quicksort and mergesort algorithms 5. Basic Data Structures: Arrays

More information

Heaps and Priority Queues

Heaps and Priority Queues Heaps and Priority Queues (A Data Structure Intermezzo) Frits Vaandrager Heapsort Running time is O(n lg n) Sorts in place Introduces an algorithm design technique» Create data structure (heap) to manage

More information

General Advise: Don t reinvent the wheel

General Advise: Don t reinvent the wheel General Advise: Don t reinvent the wheel Use libraries: Discover the available open source libraries for your application Examples: STL, boost, thrust libraries Info on C++ and STL: http://www.cplusplus.com/reference,

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

DataStruct 8. Heaps and Priority Queues

DataStruct 8. Heaps and Priority Queues 2013-2 DataStruct 8. Heaps and Priority Queues Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. November 13, 2013 Advanced Networking Technology

More information

Class string and String Stream Processing Pearson Education, Inc. All rights reserved.

Class string and String Stream Processing Pearson Education, Inc. All rights reserved. 1 18 Class string and String Stream Processing 2 18.1 Introduction C++ class template basic_string Provides typical string-manipulation operations Defined in namespace std typedefs For char typedef basic_string

More information

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

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

Data Structures CSci 1200 Test 2 Questions

Data Structures CSci 1200 Test 2 Questions Overview Data Structures CSci 1200 Test 2 Questions Test 2 will be held Thursday, March 10, 2010, 12:00-1:30pm, Darrin 308. No make-ups will be given except for emergency situations, and even then a written

More information

CS 103 Unit 12 Slides

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

More information

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

PIC10B/1 Winter 2014 Final Exam Study Guide

PIC10B/1 Winter 2014 Final Exam Study Guide PIC10B/1 Winter 2014 Final Exam Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-24 inclusive) 2. Examples/Homework 3. Textbook The final exam will test 1. Your ability to read a program

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing STL and Iterators Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer Semester

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