Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Standard Template Library


Published on

STL Intro

Published in: Technology, Education
  • Be the first to comment

Standard Template Library

  1. 1. Standard Template LibraryG uided By :- Submitted By:-Prof. Shweta Jogleker Kumar Gaurav Roll no :- 26
  2. 2. Introduction Standard Template Library (STL) stands for standard template library and is basically a library of many useful containers or algorithms. In layman terms , it basically is a class template with functions already created making life easier as they need to be merely called to be used. (Our definition) The STL achieves its results through the use of templates. This approach is very powerful, delivering compile-time polymorphism that is often more efficient than traditional run- time polymorphism. Modern C++ compilers are tuned to minimize any abstraction penalty arising from heavy use of the STL.
  3. 3. Introduction The Three Component of STLContainers A container is a holder object that stores a collection otherobjects (its elements). They are implemented as class templates,which allows a great flexibility in the types supported as elements.> Iterators They are a generalization of pointers: they are objects that pointto other objects. As the name suggests, iterators are often used toiterate over a range of objects: if an iterator points to one element in arange, then it is possible to increment it so that it points to the nextelement.> Algorithms The header <algorithm> defines a collection of functionsespecially designed to be used on ranges of elements.
  4. 4. Introduction
  5. 5. IntroductionThe Standard Template Library was created as the first library ofgeneric algorithms and data structures, with four ideas in mind:generic programming, abstractness without loss of efficiency, theVon Neumann computation model, and value semantics Function Objects Iterators Algorithm Containers
  6. 6. Introduction Algorithms use iterators to interact with objects Container stored in containers Container Iterator AlgorithmObjects Iterator Algorithm Iterator Iterator Algorithm
  7. 7. Introduction• Algorithms • Separation of concerns sort, find, search, copy, … – Algorithms manipulate data, but don’t know about containers – Containers store data, but iterators don’t know about algorithms – Algorithms and containers interact through iterators• Containers • Each container has its vector, list, map, hash_map, … own iterator types 8
  8. 8. Containers Iterators Algorithm
  9. 9. Containers• Sequence Containers – Vectors, Linked Lists, and derivatives• Container Adaptors – Queue, Priority Queue, Stack• Associative Containers – Hash, Map, Set
  10. 10. Containers (hold sequences in difference ways)• vector 0 1 2 3• list(doubly linked) 0 1 2• set 6(a kind of tree) 2 7 0 1 5 3 4 11
  11. 11. ContainersStandard Library Descriptioncontainer classS u ce C n in eq en o ta ersvector rap in id sertio s an d n d eletio s at b n ack direct access to an elem t y endeque rap in id sertio s an d n d eletio s at fro t o b n n r ack direct access to an elem t y enlist d u ly lin ed list, rap in o b k id sertio an d n d eletio an w ere n y hA cia sso tive C n in o ta ersset rap lo k p n d p id o u , o u licates allo ed wmultiset rap lo k p d p id o u , u licates allo ed wmap o e-to n m p g n d p n -o e ap in , o u licates allo ed rap k w , id ey-based lo k p o umultimap o e-to an m p g d p n -m y ap in , u licates allo ed rap k -b w , id ey ased lo k p o uC n in A a ters o ta er d pstack last-in-first-o t (L O u IF )queue first-in-first-o t (F O u IF )priority_queue h h ig est p rity elem t is alw s th first elem t o t rio en ay e en u
  12. 12. Containers Iterators Algorithm
  13. 13. Iterators• Iterators are similar to pointers – point to first element in a container – iterator operators uniform for all containers • * dereferences, ++ points to next element • begin() returns iterator pointing to first element • end() returns iterator pointing to last element – use iterators with sequences (ranges) • containers • input sequences - istream_iterator • output sequences - ostream_iterator
  14. 14. Iterators• Iterators are pointer-like entities that are used to access individual elements in a container.• Often they are used to move sequentially from element to element, a process called iterating through a container. vector<int> 17 array_ vector<int>::iterator 4 23 The iterator corresponding to the class vector<int> is of 12 the type vector<int>::iterator size_ 4
  15. 15. Iterators• The member functions begin() and end() return an iterator to the first and past the last element of a container v.begin() vector<int> 17 array_ 4 23 v.end() 12 size_ 4
  16. 16. Iterators• One can have multiple iterators pointing to different or identical elements in the container vector<int> i1 17 array_ 4 i2 23 12 i3 size_ 4
  17. 17. Iterators Types of Iterators Containers provide several iterators Begin, End, Reverse Begin, Reverse End 5 categories – each has specific operations Input, Output, Forward, Bidirectional, RandomInput Operations: =, ==, !=, *, ->, ++ , No assignment of *iOutput Operations: =, *, ++Forward Operations: =, ==, !=, *, ->, ++Bidirectional Operations: =, ==, !=, *, ->, ++, --Random Operations: =, ==, !=, +=, -=, *, ->, +, ++, -, --, [n], <, <=, >, >=
  18. 18. IteratorsCategory Descriptioninput Used to read an element from a container. An input iterator can move only in the forward direction (i.e., from the beginning of the container to the end of the container) one element at a time. Input iterators support only one-pass algorithms—the same input iterator cannot be used to pass through a sequence twice.output Used to write an element to a container. An output iterator can move only in the forward direction one element at a time. Output iterators support only one-pass algorithms—the same output iterator cannot be used to pass through a sequence twice.forward Combines the capabilities of input and output iterators and retains their position in the container (as state information).bidirectional Combines the capabilities of a forward iterator with the ability to move in the backward direction (i.e., from the end of the container toward the beginning of the container). Forward iterators support multi-pass algorithms.random access Combines the capabilities of a bidirectional iterator with the ability to directly access any element of the container, i.e., to jump forward or backward by an arbitrary number of elements.
  19. 19. IteratorsContainer Type of iterator supportedSequence containers vector random access deque random access list bidirectionalAssociative containers set bidirectional multiset bidirectional map bidirectional multimap bidirectionalContainer adapters stack no iterators supported queue no iterators supported no iterators supportedpriority_queue
  20. 20. Containers Iterators Algorithm
  21. 21. AlgorithmSTL algorithms are not member functions or friends of containers. They arestandalone template functions. To have access to the STL algorithms, wemust include <algorithm> in our program.Accept STL Iterators as arguments Sort(begin, end);4 categories Non-modifying For each, Find, Count, Equal, Search, etc. Mutating Copy, Generate, Reverse, Remove, Swap, etc. Sorting Related Sort, Stable sort, Binary search, Merge, etc. Numeric Accumulate, Inner product, Partial sum, Adjacent difference
  22. 22. Algorithm1. Retrieve or Non-Mutating algorithms: Algorithms don’t modify the contents of containers they work on. Ex: searching a container for a particular element and returning its position. Functions: count : The count() function returns the number of elements between start and end that match val. equal: The equal () function returns true if the elements in two ranges are the same. The first range of elements is those between start1 and end1. The second range of elements has the same size as the first range but starts at start2. find: The find() algorithm looks for an element matching val between start and end. If an element matching val is found, the return value Is an iterator that points to that element. Otherwise, the return value is an iterator that points to end.
  23. 23. Algorithm2. Mutating algorithms Allows modifying the contents of the containers they work on. Ex: Reversing the contents of containers. copy: The copy() function copies the elements between start and end to dest. In other words, after copy() has run, copy_backward: copy_backward() is similar to (C++ Strings) copy(), in that both functions copy elements from start to end to dest. The copy_backward() function , however, starts depositing elements at dest and then works backwards, such that: fill : The function fill() assigns val to all of the elements between start and end. generate: The generate() function runs the Generator function object g a number of times, saving the result of each execution in the range [start,end). Replaces all elements with the result of an operations
  24. 24. AlgorithmSorting algorithmsInclude general sorting, merges, dictionary comparisons, and binary searchOperations.Requires random access iterators. Functionsbinary_search : The binary_search() function searches from start to end for val.The elements between start and end that are searched should be in ascending orderas defined by the < operator. Note that a binary search will not work unless theelements being searched are in order.If val is found, binary_search() returns true, otherwise false. If the function f isspecified, then it is used to compare elements. merge : The merge() function combines two sorted ranges [start1,end1) and [start2,end2) into a single sorted range, stored starting at result. The return value of this function is an iterator to the end of the merged range. If the strict weak ordering function object cmp is given, then it is used in place of the < operator to perform comparisons between elements.
  25. 25. AlgorithmNumeric Algorithms:accumulate : The accummulate() function computes the sum of val and all of theelements in the range [start,end).adjacent_difference: The adjacent_difference() function calculates the differencesbetween adjacent elements in the range [start,end) and stores the result starting atresult.partial_sum: The partial_sum() function calculates the partial sum of a rangedefined by [start,end), storing the output at result.
  26. 26. Summary The standard template library (STL) is the C++ library that provides generic programming for many standard data structures and algorithms. Containers come in two major families: sequence (are ordered) and associative (have keys for looking up elements). Iterators can be thought of as an enhanced pointer type. The algorithms use iterators to access containers. 27
  27. 27. Success Story• Millions of copies out• Everybody (Microsoft, IBM, Sun …) ships it• A dozen books• Very few extensions• No language progress• No effect on software engineering 28