Standard Template Library Prepared By Mr K A

Standard Template Library Prepared By Mr. K. A. Hule (ME-CSE)

• 06 February 2022 Unit Prerequisite & Objectives A working knowledge of template classes is a prerequisite for • To understand what is mean by STL. • To understand the Components of STL. • To Use the various types of Containers. • To Use the various algorithms for performing various tasks. • To understand the usage of iterators. • To understand road map of OOP to the future. Standard Template Library working with STL. 2

• Introduction to STL: Components of STL • Containers: 06 February 2022 Unit VI Contents Sequence container, associative containers & Container adapters • Algorithms: • Iterators: Input, output, forward, bidirectional & random access. • Object Oriented Programming: A road map to future. Standard Template Library Basic searching & Sorting, min-max, set operations, heap sort 3

• Collect data into containers • Organize data 06 February 2022 Common tasks For printing For fast access Retrieve data items By index (e. g. , get the Nth element) By value (e. g. , get the first element with the value "Chocolate") By properties (e. g. , get the first elements where “age<64”) • Add data • Remove data • Sorting and searching • Simple numeric operations Standard Template Library • 4

• We 06 February 2022 Observation can (already) write programs that are very similar independent of the data type used Using a Selection. Sort<int> isn’t that different from using a Selection. Sort<float> Standard Template Library Using an int isn’t that different from using a float 5

• Data can be represented in variety of real-world 06 February 2022 Introduction to STL information. • Hence this data has been stored and manipulated into memory, for that’s why the term Data structure appears. In order to do so, C++ users uses generic programming, Alexander Stepanov & Meng Lee of HP developed the new concept i. e. STL. • Standard Template Library (STL): a library containing templates for frequently used data structures and algorithms Standard Template Library • 6

• STL could be used as standard approach for storing & 06 February 2022 Introduction to STL Continued… processing data. • It is a generalized library and so, its components are parameterized. • STL components are now part of Standard C++ library and they are defined in the namespace std. Basically STL consists 3 basic Components: 1. Container 2. Algorithms 3. Iterators • These 3 components work in conjunction with eachother to provide support to a variety of programming solutions. Standard Template Library • 7

• Container: 06 February 2022 Components of STL Continued… Collection of objects of different types. A container is a way that stored data is organized in memory. Implemented by template classes, so they can be easily customized to hold different kinds of data. • Algorithm: Procedures that are applied onto containers to process their data in various ways. Algorithms are represented by template functions. • Iterators: Iterator is an object(like pointer) that points to an element in a container. Used to move through the contents of containers. They are handled like pointer, we can increment or decrement them. They connect algorithms with containers and play important role. Standard Template Library For exam, there are some algorithms to sort, copy, search, & merge data. 8

Standard Template Library 06 February 2022 Components of STL 9

Standard Template Library 06 February 2022 Containers 10

A container is a way to store data, whether the data consists 06 February 2022 Containers of built-in types such as int and float, or of class objects. STL defines 10 containers which are grouped into 3 categories as shown in figure. Each container class defines a set of function that can be used to manipulate its contents. Sequence Container Associative Container Derived Container Vector, List and deque Set, Multiset, Map & Multimap Stack, Queue and Priority Queue Standard Template Library Container 11

Container Description List Linear list, allows insertion and deletions anywhere. Iterator <vector> Random Access <list> Bidirection al Standard Template Library Vector It is dynamic array. Allows insertion & deletion at back. Header File 06 February 2022 Container Continued… First element out is Priority_queue always the highest priority element. <queue> No iterator 12

• Stores a set of elements in what you can visualize as a line, like houses 06 February 2022 Sequence Container on a street. • Each element is related to the other elements by its position along the line. Each element (except at the ends) is preceded by one specific element and followed by another. • They all expand themselves to allow insertion of elements and all of • Elements in all these containers can be accessed using an iterator. • It consists of all the classes who represent the sequence or linear list. Standard Template Library them support number operations on them. 13

(hold elements sequential way) vector 0 • 2 3 list (doubly linked) • 1 Deque 0 1 2 Standard Template Library • 06 February 2022 Containers 14

Table summarizes the characteristics of the STL sequence containers. It includes the ordinary C++ array for comparison. 06 February 2022 • Standard Template Library Sequence Container Continued… 15

• Instantiating an STL container object is easy. 1. First you must include an appropriate header file. 2. Then you use the template format with the kind of objects 06 February 2022 Sequence Container Continued… to be stored as the parameter. • Examples might be or list<airtime> departure_list; //create a list of airtimes • Notice that there’s no need to specify the size of STL containers. The containers themselves take care of all memory allocation. Standard Template Library vector<int> a. Vect; //create a vector of ints 16

06 February 2022 Vector • Vectors are same as dynamic arrays. • With the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. • Vector elements are placed in contiguous storage so that they can • In vectors, data is inserted at the end. • How to declare: • Example: #include <vector>. . . vector<int> scores (100); //100 integer scores vector<Passenger>passenger. List(20); //list of 20 passengers Standard Template Library be accessed and traversed using iterators. 17

• Allows direct access to the elements via an index 06 February 2022 Vector operator([]) • Indices for the vector elements are in the range from 0 to size() -1 • Example: #include <vector> v[5]=15; • Vector provides various functions: 1. Modifier Function 2. Element Access 3. Capacity 4. Iterators Standard Template Library vector <int> v(20); 18

Function Description Example 1 assign() It assigns new value to the vector elements by replacing old ones vector <int> g 1; g 1. assign(5, 10) 2 push_back() It push the elements into a vector from the back g 1. push_back(10) 3 pop_back() It is used to pop or remove elements from a vector from the back. g 1. pop_back() 4 insert() It inserts new elements before the element at the specified position g 1. insert(g 1. begin(), 5) erase() It is used to remove elements from a vector<int>: : iterator it 1; container from the specified position or it 1=g 1. begin()+2; range. g 1. erase(it 1); 6 swap() It is used to swap the contents of one vector with another vector of same type and size. g 1. swap(g 2); 7 clear() It is used to remove all the elements of the vector container g 1. clear() 5 06 February 2022 No Standard Template Library Vector Functions- Modifiers 19

Function Description Example 1 size() Returns the number of elements in the vector. cout<<g 1. size(); 2 max_size() Returns the maximum number of elements that the vector can hold. cout<<g 1. max_size(); 3 capacity() Returns the size of the storage space currently allocated to the vector expressed as number of elements. cout<<capacity(); 4 resize() Resizes the container so that it contains g 1. resize(5); n elements. 5 empty() Returns whether the container is empty cout<<g 1. empty(); 6 shrink_to_fi t() Reduces the capacity of the container to fit its size and destroys all elements g 1. shrink_to_fit(); beyond the capacity 7 reserve() Requests that the vector capacity be at least enough to contain n elements. g 1. reserve(10) 06 February 2022 No Standard Template Library Vector Functions- Modifiers 20
![• Element access: 1. reference operator [g] – Returns a reference to the • Element access: 1. reference operator [g] – Returns a reference to the](http://slidetodoc.com/presentation_image_h2/a6c732e6aa59738b26531f2ab6ede598/image-21.jpg)
• Element access: 1. reference operator [g] – Returns a reference to the element at position 06 February 2022 Vector Functions ‘g’ in the vector 2. at(g) – Returns a reference to the element at position ‘g’ in the vector 3. front() – Returns a reference to the first element in the vector 4. back() – Returns a reference to the last element in the vector Iterators 1. begin() – Returns an iterator pointing to the first element in the vector 2. end() – Returns an iterator pointing to theoretical element that follows the last element in the vector 3. rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element 4. rend() – Returns a reverse iterator pointing to theoretical element preceding the first element in the vector (considered as reverse end) Standard Template Library • 21

• They are sequence containers that allow non-contiguous memory 06 February 2022 Lists allocation. • As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. • Normally, when we say a List are the doubly linked list. For implementing a singly linked list, we use forward list. Advantage: ability to add and remove items efficiently at any position in the sequence • How to Create? #include<iostream. h> #include<list> std: : list<int> l{1, 2, 3}; Standard Template Library • 22

1. front() – Returns the value of the first element in the list 2. back() – Returns the value of the last element in the list 3. push_front(g) – Adds a new element ‘g’ at the beginning of the list 4. push_back(g) – Adds a new element ‘g’ at the end of the list 5. pop_front() – Removes the first element of the list, and reduces size of the list by 1 6. pop_back() – Removes the last element of the list, and reduces size of the list by 1 7. begin() – Returns an iterator pointing to the first element of the list 8. end() – Returns an iterator pointing to theoretical last element which follows 06 February 2022 Lists Functions 9. empty() – Returns whether the list is empty(1) or not(0) 10. insert() – Inserts new elements in the list before the element at a specified position 11. erase() – Removes a single element or a range of elements from the list 12. assign() – Assigns new elements to list by replacing current elements and resizes the list 13. remove() – Removes all the elements from the list, which are equal to given element 14. reverse() – Reverses the list 15. size() – Returns the number of elements in the list 16. sort() – Sorts the list in increasing order Standard Template Library the last element 23

• Double ended queues are sequence containers with the feature of 06 February 2022 Deque expansion and contraction on both the ends. • They are similar to vectors, but are more efficient in case of insertion and deletion of elements. • Basically an implementation of the data structure double ended queue. • Double ended queues are a special case of queues where insertion and • How to Create? #include<iostream. h> #include<deque> std: : deque<int> d{1, 2, 3}; Standard Template Library deletion operations are possible at both the ends. 24

Use begin() Go to beginning end() Go to end size() Use to get size of deque max_size() Used to get maximum size of deque rbegin() Used to get reverse iterator to reverse beginning resize() Used to change the size of deque empty() Used to check the whether deque is empty or not at() Get particular element front() Get first element back() Get last element push_back() Add element at end push_front() Add element at start pop_back() Remove last element pop_front() Remove first element insert() Add element swap() Swap the contents clear() Clear the contents 06 February 2022 Function Standard Template Library Functions for Deque: 25

• They are not sequential; instead it uses keys to access data. • The keys, typically numbers or stings, are used automatically by the 06 February 2022 Associative Container container to arrange the stored elements in a specific order. • It’s like an ordinary English dictionary, in which you access data by looking up words arranged in alphabetical order. • If you know the key, you can access the associated value swiftly & • There are two kinds of associative containers in the STL: sets and maps. • These both store data in a structure called a tree, which offers fast searching, insertion, and deletion. • However, these are very slow for random access and inefficient for sorting. • Implement sorted data structures that can be quickly searched (O(log n) complexity). Standard Template Library easily. 26

Table summarizes the associative containers available in the STL. • Creating associative containers is just like creating sequential ones: set<int> int. Set; //create a set of ints or typedef map<string, int> phone. Map; //create map with string as //key and int as value. 06 February 2022 • Standard Template Library Associative Container Continued… 27

(hold sequences in difference ways) set 6 (a kind of tree) 2 0 7 1 5 3 • Map (a kind of BST) 4 Standard Template Library • 06 February 2022 Containers 28

• Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. • 06 February 2022 Set The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. • Some basic functions associated with Set: 1. begin() – Returns an iterator to the first element in the set. 2. end() – Returns an iterator to theoretical element that follows last element in set. 4. max_size() – Returns the maximum number of elements that the set can hold. 5. empty() – Returns whether the set is empty. • How to Create? #include<iostream. h> #include<set> set<int> int. Set; //create a set of ints Standard Template Library 3. size() – Returns the number of elements in the set. 29

• Multisets are a type of associative containers similar to set, with an 06 February 2022 Multiset exception that multiple elements can have same values. • Some basic functions associated with multiset: 1. begin() – Returns an iterator to the first element in the multiset 2. end() – Returns an iterator to theoretical element that follows last element in the multiset 4. max_size() – Returns the maximum number of elements that the multiset can hold 5. empty() – Returns whether the multiset is empty. How to Create? #include<iostream. h> #include<multiset> multiset<int> int. Set; //create a multiset of ints Standard Template Library 3. size() – Returns the number of elements in the multiset 30

• Maps contain sorted key-value pair, in which each key is unique 06 February 2022 Map Container in STL and cannot be changed, and it can be inserted or deleted but cannot be altered. Lets take an example: • A map of students where: • roll number is the key and • name is the value. • Keys are always arranged in sorted order • In case the keys are of string type, they are sorted lexicographically. • Each element has a key value and a mapped value. No two mapped values can have same key values. map: : operator[] Standard Template Library • 31

• Syntax: 06 February 2022 How to create C++ map? map<key_type , value_type> map_name; • This will create a map with key of type Key_type and value of type value_type. • key of a map and corresponding values are always inserted as a pair, you cannot insert only key or just a value in a map. Example: • create a map m with keys 1, 2, 3 and their corresponding values 2, 3, 4 map<int, int> m { {1, 2} , {2, 3} , {3, 4} }; • create a map with keys of type character and values of type integer map<string, int> map 1; map 1["abc"]=100; // inserts key = "abc" with value = 100 map 1["b"]=200; // inserts key = "b" with value = 200 map 1["c"]=300; // inserts key = "c" with value = 300 map 1["def"]=400; // inserts key = "def" with value = 400 Standard Template Library • 32

a) begin(): Returns an iterator to the first element in the map. b) end(): Returns an iterator pointing to the past-end. c) size(): Returns the number of elements in the map. d) empty(): Returns a boolean value indicating whether the map is empty. e) insert( pair(key, value)): Adds a new key-value pair to the map. An 06 February 2022 Map Functions alternate way to insert values in the map is: map_name[key] = value; f) find(val): Gives the iterator to the element val, if it is found otherwise it g) erase(iterator position): Removes the element at the position pointed by the iterator. h) erase(const g): Removes the key value g from the map. i) clear(): Removes all the elements from the map. Standard Template Library returns m. end() 33

• Multimap is similar to map with an addition that multiple elements can have same keys. • Also, it is NOT required that the key value and mapped value pair has to be 06 February 2022 Multimap unique in this case. • One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap makes it very much useful in competitive programming. • Some Basic Functions associated with multimap: 1. begin() – Returns an iterator to the first element in the multimap 2. end() – Returns an iterator to theoretical element that follows last element in the 3. size() – Returns the number of elements in the multimap 4. max_size() – Returns the maximum number of elements that the multimap can hold 5. empty() – Returns whether the multimap is empty 6. pair<int, int> insert(keyvalue, multimapvalue) – Adds a new element to the multimap #include<iostream. h> #include<multiset> multimap <int, int> gquiz 1; // empty multimap container Standard Template Library multimap 34

06 February 2022 It’s possible to create special-purpose containers from the normal containers. • Have simpler interfaces than the more general containers. • Implemented with container adapters in the STL are stacks, queues, and priority queues. • Stacks, queues, and priority queues can be created from different sequence containers, • Standard Template Library Container Adapter 35

• You use a template within a template to instantiate 06 February 2022 Container Adapter Continued… these classes. • For example, here’s a stack object that holds type int, instantiated from the deque class: stack< deque<int> > a. Stak; A detail to note about this format is that you must insert a space between the two closing angle brackets. You can’t write stack<deque<int>> astak; //syntax error • because the compiler will interpret the >> as an operator. Standard Template Library • 36

• stack • Queue 06 February 2022 (hold sequences in difference ways) Standard Template Library Containers 37

• Allows access at only one end of the sequence (top) • Adds objects to container by pushing the object onto the stack • Removes objects from container by popping the stack • LIFO ordering (last end, first out) • How to Create? 06 February 2022 Stack stack<object_type> stack_name; The above statement will create a stack named stack_name of type • Functions: 1. empty(): Check for empty stack 2. top(): Get top Element 3. push(): Add top Element 4. pop(): Remove top Element 5. size(): Get Size of stack 6. swap(): swaps the elements of the two stacks. Standard Template Library object_type. 38

• Allows access only at the front and rear of the sequence • Items enter at the rear and exit from the front • Example: waiting line at a grocery store • FIFO ordering (first-in first-out ) • How to Create? 06 February 2022 Queue queue< object_type > queue_name; The above statement will create a queue named queue_name of type • Functions: 1. empty(): Check for empty queue 2. front() returns the front element of the queue 3. back() returns the element at the back of the queue. 4. push(): Add back or rear side Element 5. pop(): Remove front side Element 6. size(): Get Size of Queue 7. swap(): swaps the elements of the two Queue. Standard Template Library object_type. 39

• priority_queue is just like a normal queue except the element removed from the queue is always the greatest among all the elements in queue, thus this 06 February 2022 Priority Queue container is usually used to replicate Max Heap in C++. • Elements can be inserted at any order and it have O(log(n)) time complexity for insertion. • How to Create? priority_queue<object_type> pq; The above statement will create a priority queue named pq of type object_type. Functions: 1. empty() function returns whether the queue is empty. 2. size() function returns the size of the queue. 3. push(g) function adds the element ‘g’ at the end of the queue. 4. pop() function deletes the first element of the queue. 5. swap()This function is used to swap the contents of one priority queue with another priority queue of same type and size. Standard Template Library • 40

Standard Template Library 06 February 2022 Algorithms 41

• • An algorithm is a function that does something to the items in a container (or containers). Algorithms in the STL are not member functions or even friends of container classes, as they are in earlier container libraries. They are just standalone template functions, which are included in <algorithm> header file. STL algorithms reinforce the philosophy of reusability. Various Categories of Algorithms: 1. Mutating Sequence Algorithms 2. Non-Mutating Sequence Algorithms 3. Sorting Algorithms 4. Numerical Algorithms 5. Set Algorithms 6. Relational Algorithms 06 February 2022 • Standard Template Library Algorithm 42

copy() copies the sequence of elements copy_backward() copies the list in backward direction fill() Fills a sequence with a specified value fill_n() Fills first n elements with the result of an operation generate() Replaces all elements with the result of an operation iter_swap() Swaps elements pointed to by iterators random_shuffle() Places elements in random order remove() Deletes elements of a specified value replace() Replaces elements with specified value reverse() Reverse() this function is used to reverse the given sequence rotate() Rotates elements swap() Swaps 2 elements transform() Applies an operation to all elements unique() it finds the adjacent duplicate elements and remove them 06 February 2022 Mutating Sequence Algorithms Standard Template Library Algorithm Continued… 43

adjacent_find() Finds adjacent pair of objects that are equal count() Counts occurrence of a value in a sequence count_if() Counts number of elements that matches a predicate equal() True if 2 ranges are the same find() Finds first occurrence of a value in a sequence find_end() Finds last occurrence of a value in a sequence for_each() Apply an operation to each element mismatch() Finds first elements for which 2 sequences differ search() Finds a subsequence within a sequence search_n() Finds a sequence of a specified number of similar elements. 06 February 2022 Non-Mutating Sequence Algorithms Standard Template Library Algorithm Continued… 44

binary_search( ) Conducts a binary search on an ordered sequence equal_range( ) Finds a subrange of elements with a given value inplace_merge() Merges two consecutive sorted sequences lower_bound() Finds the first occurrence of a specified value make_heap() Makes a heap from a sequence merge() Merges two sorted sequences nth_element( ) Puts a specified element in its proper place partial_sort( ) Sorts a part of a sequence partial_sort_copy() Sorts a part of a sequence and then copies Partition( ) Places elements matching a predicate first pop_heap( ) Deletes the top element push_heap() Adds an element to heap sort( ) Sorts a sequence sort_heap( ) Sorts a heap stable_partition() Places elements matching a predicate first matching relative order stable_sort( ) Sorts maintaining order of equal elements upper_bound() Finds the last occurrence of a specified value 06 February 2022 Sorting algorithms Standard Template Library Algorithm Continued… 45

Set algorithms includes( ) Finds whether a sequence is a subsequence of another set_difference( ) Constructs a sequence that is the difference of two ordered sets Set_intersection( ) Constructs a sequence that contains the intersection of ordered sets set. symmetric_ difference ( ) Produces a set which is the symmetric difference between two ordered Sets set_union() Produces sorted union of two ordered sets 06 February 2022 Algorithm Continued… Relational algorithms Finds whether two sequences are the same lexicographical_com Compares alphabetically one sequence with other pare( ) max( ) Gives maximum of two values max_element( ) Finds the maximum element within a sequence min( ) Gives minimum of two values min _element( ) Finds the minimum element within a sequence mismatch( ) Finds the first mismatch between the elements in two sequences Standard Template Library equal( ) 46

Numeric algorithms accumulate( ) Accumulates the results of operation on a sequence adjacent_difference( ) Produces a sequence from another sequence inner_product( ) Accumulates the results of operation on a pair of sequences partial_sum( ) Produces a sequence by operation on a pair of sequences 06 February 2022 Algorithm Continued… • Suppose you create an array of type int, with data in it: • You can then use the STL sort() algorithm to sort this array by saying sort(arr, arr+8); Standard Template Library int arr[8] = {42, 31, 7, 80, 2, 26, 19, 75}; 47

• The for_each() algorithm allows you to do something to every item in a container. • You write your own function to determine what that “something” is. • Your function can’t change the elements in the container, but it can 06 February 2022 for_each() Algorithm use or display their values. • Syntax: for_each (Input. Iterator first, Input. Iterator last, Function fn) • Parameters : executed. last : This ending position till where function has to be executed. fn/obj_fnc : The 3 rd argument is a function or an object function which operation would be applied to each element. • For Example: used to convert all the values of an array from inches to centimeters and display them. Standard Template Library first : The beginning position from where function operations has to be 48

• The transform() algorithm does something to every item in a container, and places the resulting values in a different container (or the same one). • 06 February 2022 The transform() Algorithm Again, a user-written function determines what will be done to each item. The return type of this function must be the same as that of the destination container. • The transform function works in two modes. Unary / Binary operation mode • Syntax: transform(Iterator input. Begin, Iterator input. End, Iterator Output. Begin, transform(Iterator input. Begin 1, Iterator input. End 1, Iterator input. Begin 2, Iterator Output. Begin, binary_operation) • For Example: Similar to FOR_EACH, except that instead of displaying the converted values, our in_to_cm() function puts the centimeter values into a different array Standard Template Library unary_operation) 49

• Here’s an algorithm that works with three containers, merging the elements from two source containers into a destination container. • 06 February 2022 The merge() Algorithm Syntax: merge (initer 1 beg 1, initer 1 end 1, initer 2 beg 2, initer 2 end 2, outiter res) merge (initer 1 beg 1, initer 1 end 1, initer 2 beg 2, initer 2 end 2, outiter res, Compare comp) • Parameters : beg 1 : Input iterator to initial position of first sequence. end 1 : Input iterator to final position of first sequence. end 2 : Input iterator to final position of second sequence. res : Output Iterator to initial position of resultant container. comp : The comparator function that returns a boolean true/false of the each elements compared. This function accepts two arguments. This can be function pointer or function object and cannot change values. Return value : Iterator to last element of the resulting container. • The MERGE example shows how it works. Standard Template Library beg 2 : Input iterator to initial position of second sequence. 50

• You can guess what the sort() algorithm does. • This function of the STL, sorts the contents of the given range. There are 06 February 2022 The sort() Algorithm two version of sort() : 1. sort(start_iterator, end_iterator ) : sorts the range defined by iterators start_iterator and end_iterator in ascending order. 2. sort(start_iterator, end_iterator, compare_function) : this also sorts the given range but you can define how the sorting should be done by compare_function. Here’s an example, called SORT, of this algorithm applied to an array The count() Algorithm • • count() returns the number of elements in the given range that are equal to given value. Syntax for count is: count(first , last , value) : This will return number of the element in range defined by iterators first and last ( excluded ) which are equal ( == ) the value. The COUNT example shows how this looks Standard Template Library • 51

• The find() algorithm looks for the first element in a container that has a specified 06 February 2022 The find() Algorithm value. • Returns an iterator to the first element in the range [first, last) that compares equal to val. If no such element is found, the function returns last. • Syntax: Input. Iterator find (Input. Iterator first, Input. Iterator last, const T& val) • Parameters : searched is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. val : Value to be search in the range Return Value : An iterator to the first element in the range that compares equal to val. If no elements match, the function returns last. • The FIND example program shows how this looks when we’re trying to find a value in an array of ints. Standard Template Library first, last : Input iterators to the initial and final positions in a sequence. The range 52

• • Some algorithms operate on two containers at once. For instance, while the find() algorithm looks for a specified value in a single container, the search() algorithm looks for a sequence of values, specified by one container, within another container. Syntax: Forward. Iterator 1 search (Forward. Iterator 1 first 1, Forward. Iterator 1 last 1, Forward. Iterator 2 first 2, Forward. Iterator 2 last 2); Forward. Iterator 1 search (Forward. Iterator 1 first 1, Forward. Iterator 1 last 1, Forward. Iterator 2 first 2, Forward. Iterator 2 last 2, Binary. Predicate pred); Parameters: • first 1: Forward iterator to beginning of first container to be searched into. • last 1: Forward iterator to end of first container to be searched into. • first 2: Forward iterator to the beginning of the subsequence of second container to be searched for. • last 2: Forward iterator to the ending of the subsequence of second container to be searched for. • pred: Binary function that accepts two elements as arguments (one of each of the two containers, in the same order), and returns a value convertible to bool. The returned value indicates whether the elements are considered to match in the context of this function. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: • an iterator to the first element of the first occurrence of [first 2, last 2] in [first 1, last 1], or last 1 if no occurrences are found. The SEARCH example shows how this looks. 06 February 2022 • • Standard Template Library The search() Algorithm 53

• This function returns Boolean true if the element is present in the given range, else Boolean false is returned. There are two variations of 06 February 2022 The binary_search() Algorithm binary_search(): • binary_search(first, last, value): this version returns true if there is an element present, satisfying the condition (!(a < value) &&!(value < a)) in the given range, i. e. from first to last, in other words, operator(<) is used to check the • binary_search(first, last, value, compare_function) : this version return true if there is an element present in the given range, i. e. from first to the last. • Note that first and last are iterators and the element pointed by last is excluded from the search. • The binary_search example shows how this looks. Standard Template Library equality of the two elements. 54

• Heap sort is a comparison based sorting technique based on 06 February 2022 The Heap Sort Algorithm Binary Heap data structure. • It is similar to selection sort. First find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. What is Binary Heap? A Binary Heap is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called as max heap and the latter is called min heap. The Standard Template Library • heap can be represented by binary tree or array. 55

• Heap Sort Algorithm for sorting in increasing order: 06 February 2022 The Heap Sort Algorithm Continued… 1. Build a max heap from the input data. 2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree. 3. Repeat above steps while size of heap is greater than 1. • How to build the heap? nodes are heapified. So the heapification must be performed in the bottom up order. • Using C++ STL we perform those activities very easily. To perform those operation we use make_heap() & sortheap() STL algorithms. • Standard Template Library Heapify procedure can be applied to a node only if its children Program for Heap Sort using STL Algorithms. 56

• Sets are a type of associative containers in which each element has 06 February 2022 The Set Operations to be unique, because the value of the element identifies it. • The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. • Different set operations can be performed using STL set class & • Operations like union, intersection, set difference , etc. • Program for set operations. Standard Template Library algorithms. 57

• The minmax() algorithm used to get both smallest and largest element. 06 February 2022 The min-max Algorithm minmax(a, b): This function returns a pair, in which 1 st element is of minimum of the two elements and the 2 nd element is maximum of 2 elements. minmax(array of elements): This function returns similarly as 1 st version. Only difference is that in this version, the accepted argument is a list of integers/strings among which maximum and minimum elements in list without sorting. • Syntax: pair <const T&, const T&> minmax (const T& a, const T& b); • This algorithm work with C++11 onwards. • Example for finding minimum and maximum. Standard Template Library minimum are obtained. Useful in cases when we need to find 58

Standard Template Library 06 February 2022 Iterators 59

06 February 2022 Iterators • Iterators are pointer-like entities that are used to access individual data items from a container. • Often they are used to move sequentially from element to element, a process called iterating through the container. You can increment iterators with the ++ operator so they point to the next element, and dereference them with the * operator to obtain the value of the element they point to. • In the STL an iterator is represented by an object of an iterator class. Standard Template Library • 60

Iterators are 5 types: Standard Template Library • 06 February 2022 Iterators Continued… Fig: Functionality Venn diagram of iterators 61

Operations supported by iterators: 06 February 2022 • Standard Template Library Iterators Continued… 62

Standard Template Library 06 February 2022 Working of Iterator 63

Standard Template Library 06 February 2022 Working of Iterator 64

Input Iterator is an iterator used to read the values from the container. Dereferencing an input iterator allows us to retrieve the value from the container. It does not alter the value of a container. It is a one-way iterator. An input Iterator is produced by the istream_iterator is a single-pass input iterator that reads successive objects of type T from the std: : basic_istream object for which it was constructed, by calling the appropriate operator>>. • The actual read operation is performed when the iterator is incremented, not when it is dereferenced. • The first object may be read when the iterator is constructed or when the first dereferencing is done. • Otherwise, dereferencing only returns a copy of the most recently read object. • • • 06 February 2022 istream_iterator (constructor) constructs a new istream_iterator (public member function) (destructor) (implicitly declared) destructs an istream_iterator, including the cached value (public member function) operator*operator-> returns the current element (public member function) operator++(int) advances the iterator (public member function) Non-member functions operator==operator!= compares two istream_iterators (function template) Standard Template Library Member functions 65

An ostream iterators are the output iterators used to write to the output stream such as cout successively. • An ostream iterator is created using a basic_ostream object. • When an assigenment operator is used on the ostream iterator, it inserts a new element into the output stream. • Syntax: • 06 February 2022 The ostream_iterator template<class T, class char. T=char, class traits=char_traits<char. T>> class ostream_iterator; Member functions of Ostream Iterator class 1. Ostream_iterator<T, char. T, traits>& operator=(const T& value); 2. Ostream_iterator<T, char. T, traits>& operator*(); 3. Ostream_iterator<T, char. T, traits>& operator++(); 4. Ostream_iterator<T, char. T, traits>& operator++(int); • Parameters T: It is the type of elements to be inserted into the container. char. T: The type of elements that ostream can handle, for example, char ostream. traits: These are the character traits that the stream handles for the elements. Standard Template Library • 66

• Features Of Output Iterator Dereferencing : *X=7; Incrementable : X++; /++X; Limitations Of Output Iterator 1. Assigning but no accessing 1. It cannot be decremented : *A = x; // valid x = *A; // invalid : A--; / --A // not valid 2. Equality/Inequality Operator: X==Y; invalid X!=Y; invalid 3. Multi-pass algorithm: An output iterator cannot be used as a multi -pass algorithm. 4. Relational Operators: An output iterator cannot be compared by using any of the relational operators. 5. Arithmetic Operators: An output iterator cannot be used with the arithmetic operators. A + 2; // invalid A + 5; // invalid Standard Template Library • 06 February 2022 The ostream_iterator 67

• 06 February 2022 Object Oriented Programming- Road Map to Future Object oriented strategies means, you will have objects which are independent and you will be able to use the operations on them. When working with this kind of programming language, then you should be able to create objects of any class and then you should be calling those interfaces by changing the objects. • Here the word independent means that you will write the code just once and you will be able to run it anywhere. Standard Template Library • 68

• 1. Client-Server Systems 2. Object Oriented Databases 3. Real-Time System Design 4. Simulation And Modelling System 5. Hypertext And Hypermedia 6. Neural Networking And Parallel Programming 7. Office Automation Systems 8. CIM/CAD/CAM Systems 9. AI Expert Systems 06 February 2022 Here Are Some Applications Of Object Oriented Programming: Standard Template Library Object Oriented Programming- Road Map to Future 69

Text Books: 1. 06 February 2022 Resources Donald E. Knuth, “The Art of Computer Programming”, Vols. 1, Addison -Wesley. 2. Brian W. Kernighan, Dennis M. Ritchie, “The C Programming Language”, Prentice Hall, Second Edition 1. Lamey Robert, “Logical problem solving”, Prentice Hall. 2. Herbert Schildt, “C/C++ Programmer's Reference”, Mc. Graw-Hill. 3. Balguruswamy, “C Programming Language Concepts”, Mc. Graw-Hill. 4. Kanetkar, “Lets C Concepts”, “Test your C Skills”, BPB Publications Weblink: www. hulekuldeep. weebly. com https: //www. cs. helsinki. fi/u/tpkarkka/alglib/k 06/lectures/algorithms. html Standard Template Library Reference Books: 70

06 February 2022 Thank You For any Query contact me Contact No: 8668277166 Standard Template Library www. hulekuldeep. weebly. com 71
- Slides: 71