1 / 92

Advanced STL

Advanced STL. Overview of Containers, Iterators, Algorithms. Using Functionality in STL. Learning & Development Team. http://academy.telerik.com. Telerik Software Academy. Table of Contents (1). Containers Concepts Priority queue (multi)Sets, (multi)Maps Iterators Concepts

aviv
Download Presentation

Advanced STL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced STL Overview of Containers, Iterators, Algorithms. Using Functionality in STL Learning & Development Team http://academy.telerik.com Telerik Software Academy

  2. Table of Contents (1) • Containers • Concepts • Priority queue • (multi)Sets, (multi)Maps • Iterators • Concepts • STL container iterators • Insertion iterators and iterators on streams

  3. Table of Contents (2) • Algorithms • Heap creation • Sorting, Operations on sorted containers • Searching • Combinatorial • Functors • Concepts • Creating and using Generators, Unary and Binary Functors

  4. Containers STL Container Architecture, Advanced Containers

  5. Containers • STL Containers represent collections of objects • Going through objects is called iterating • Several base concepts & refinements for all STL containers: • Container • Forward Container, Reversible Container • Random Access Container • Concepts – definitions, not implementations • Refinements – extensions/specific definitions

  6. Containers • Containers also fall into one of two groups: • Sequences • Associative containers • Actual data structures are models of the above • i.e. implementations of the Concepts • e.g. a vector is a model of a Sequence

  7. Containers – Pseudo-Diagram Container Forward, Reversible, Random Access Sequence Front/Back Insertion Associative Container Simple, Pair, Sorted, Unique list vector map deque set bit_vector Adaptor multimap multiset stack queue priority_queue

  8. Containers • STL Containers are templates • A template is filled compile-time with type data • i.e. a STL container is defined once • compiled into different classes • depending on its passed template parameters • E.g. the container class vector is defined in the header <vector> once, but we can: • use a vector<int>, to store integers • use another vector<string> to store strings, etc.

  9. Containers • Container concept • Stores elements, element lifetime ends when container lifetime ends • No guarantees on element order • Forward Container concept (refinement of Container) • Elements have some order • Order won't change as a side effect of going through (iterating) the elements • Guarantees "forward direction" of iteration

  10. Containers • Reversible Container concept (refinement of Forward Container) • Guarantees two (opposite) directions of iteration – "forward" and "backward" • Random Access Container (refinement of Reversible Container) • Guarantees (amortized) constant time access to any contained element • i.e. can access an element, without iterating other elements to reach it

  11. Sequences • Sequences are refinements of Forward Containers • Have a definite ordering of elements • Have variable size – elements can be added indefinitely, at specific positions • Sequence models: • vector • list • deque

  12. Associative Containers • Associative Containers are Containers • Similar to Sequences, but cannot add elements at specific positions • Each element has a key and a value • Elements are accessed by their key • Elements can be added indefinitely, but the container decides their "position" • Several types (to be discussed later)

  13. Container Adaptors • Adaptors limit access to containers • Fundamental for FIFO and LIFO data structures • Adaptor models: • queue • stack • priority_queue

  14. Advanced Container Models priority_queue, map, set, multimap, multiset, Usage and Examples Note: for basic container models, see Basic ADTs in STL

  15. Priority Queue • The priority_queue is a queue • Enables insertion of elements • Enables access/removal of "top" element • "First" element is referred to as "top" element • Guarantees the top element is the largest • Biggest for numbers (by default) • Last lexicographically for strings (by default) • Or according to a comparer • Or overloaded operators for other types

  16. Priority Queue • Priority Queue (#include <queue>) • priority_queue<T, Sequence = vector<T>, Compare = less<T> > • T has to be able to be compared by Compare • Fast at accessing the top element (1) • Fast at inserting elements (log n) • Good at removing top element (log n) • Uses a container for storing elements (default: vector)

  17. Priority Queue • Declaring and initializing a priority queue: • Retrieving top element: • Removing top element: #include<queue> //required header … priority_queue<int> numsBySize; numsBySize.push(1); numsBySize.push(3); numsBySize.push(2); priority_queue<string> stringsByLex; stringsByLex.push("a"); stringsByLex.push("c"); stringsByLex.push("b"); numsBySize.top() //returns 3, does not remove it stringsByLex.pop() //removes "c"

  18. Priority Queue Usage Live Demo

  19. Problems Solved with Priority Queues • Finding shortest path in weighted graphs (Dijkstra's algorithm uses priority queues) • Getting largest N items from several sorted lists • Compression in Huffman coding • Heapsort (STL priority queue uses a heap) • Simple problem: • Given a sequence of numbers, each time a numbers is 0, print the largest number so-far

  20. Simple Problem Solved with a Priority Queue Live Demo

  21. Associative Container Models • Several categories • Simple, Sorted, Unique • Simple Associative Containers • Elements are their own keys • Pair Associative Container • Values are in the form (key, element) • Sorted Associative Containers • Elements ordered, most operations are log n • Unique Associative Containers • No duplicate keys are allowed

  22. Set • Categories: Sorted, Simple, Unique • Elements are their own keys • E.g. if you want to check if an element is contained, you query with the (copy) of the element • Guarantees no duplicate elements • Extracting elements one by one: • Yields the elements in ascending order

  23. Set • Set (#include <set>) • set<Key, Compare = less<Key>, Alloc = new> • Key has to be comparable by Compare • Fast checking if an element is contained (log n) • Fast inserting elements (log n) • Fast deleting (erasing) elements (log n) • Deleting elements does not invalidate iterators to other elements

  24. Set • Declaring and initializing a set: • Set elements can be accessed through iterator (and consequently iterated in ascending order) • Set elements can be removed • By iterator • By value #include<set> //required header … set<int> uniqueNums; uniqueNums.insert(3); uniqueNums.insert(7); uniqueNums.insert(2); uniqueNums.insert(7); uniqueNumbers.begin(); //iterator to first element (2) uniqueNums.erase(uniqueNums.begin()); uniqueNums.erase(2);

  25. Set Usage Live Demo

  26. Problems Solved with Sets • Any problems including mathematical set operations • Unions, intersections, etc. • Set Cover Problem • Simple problem: • You are given a sequence of numbers. Print all numbers in the sequence, without printing the same number more than once

  27. Simple Problem Solved with a Set Live Demo

  28. Multiset • Same as a set, without the Unique category • i.e. there can be repeating elements • All other operations & properties are the same • Multiset (#include <set>) • multiset (same template parameters as set) • Declaring and initializing a multiset #include<set> //required header … multiset<int> nums; nums.insert(2); nums.insert(2); //nums contains: 2, 2

  29. Multiset Usage Live Demo

  30. Map • Categories: Sorted, Unique, Pair • Each element has a key • Accessing elements is done through the key • Guarantees no duplicate elements • Element keys are iterated in increasing order • Often pictured as an array, the indices of which can be any type – number, string or even some class

  31. Map • Map (#include <map>) • map <Key, Data, Compare = less<Key>Alloc = new> • Key must be comparable by Compare • Fast at accessing elements by key (log n) • Fast at deleting elements by key (log n) • Fast at inserting elements by key (log n) • Values are of the type std::pair<Key, Data> • Iterators will point to std::pair objects

  32. Map • Declaring and initializing a map: • Accessing element by key: • Removing element by key: #include<map> //required header … map<char*, int> peopleAges; peopleAges["Joro"] = 22; peopleAges.insert(pair<char*, int>("Petya", 20)); peopleAges["Petya"]; peopleAges["Petya"]++; peopleAges.erase("Joro");

  33. Map Usage Live Demo

  34. Problems Solved with Maps • Maps have similar efficiency as hash-tables, but keep elements ordered • Many compression algorithms use maps/hash-tables • Several cryptographic attacks use maps/hash-tables • Simple Problem: • You are given a sentence of words. Count how many times each word occurs in the text.

  35. Simple Problem Solved with a Map Live Demo

  36. Multimap • Same as a map, without the Unique category • i.e. there can be repeating elements • No [] operator, as there can be multiple values, corresponding to the same key • All other operations & properties are the same • Most element access is done through iterators

  37. Multimap • Multimap (#include <map>) • multimap(same template parameters as map) • Declaring and initializing a multimap #include<map> //required header … multimap<string, string> personNicks; personNicks.insert(pair<string, string>("George", "Joro")); personNicks.insert(pair<string, string>("George", "Gosho")); personNicks.insert(pair<string, string>("George", "Joro")); personNicks.insert(pair<string, string>("George", "Gopi"));

  38. Multimap Usage Live Demo

  39. Iterators The Way of STL Element Access

  40. Iterators • Iterators are a pattern in STL • Enable access to container elements • For almost any container's elements • Most container iterators have similar mechanics to pointers • Can be incremented, to point to next element • Can be dereferenced, to get element value • Can use ->operator to access element members • Can be const

  41. Iterators • Each container defines its own iterator type • A class inside the container's class • Syntax to access iterator type • Example for an iterator of a vector<int>: container_type<template_parameters...>::iterator vector<int> numbers; numbers.push_back(1); numbers.push_back(2); vector<int>::iterator numsIter = numbers.begin(); cout<<*numsIter<<endl; numsIter++; cout<<*numsIter<<endl;

  42. Iterators: Simple Example Live Demo

  43. Iterators and Containers Syntax, Usage, Examples

  44. Iterators • Several types of iterator Concepts • with differing purposes and functionality • Output Iterator • Supports storing values • i.e. writing values to the pointed element • i.e. mutable • Supports incrementing • Other operations are not necessarily supported • i.e. no guarantee on dereferencing, comparing…

  45. Iterators • Input Iterator • Supports dereferencing • Supports incrementing • Does not necessarily support storing values • i.e. writing values to the pointed element • i.e. not necessarily mutable • Opposite of Output iterator, in some sense

  46. Iterators • Forward Iterator • Refinement of Input & Output iterators • Reflects the idea of a linear sequence of values • Allows multipass algorithms • Implementations can be mutable/immutable • Can only increment, i.e. can't "go back", only "forward"

  47. Iterators • Bidirectional Iterator • Refinement of Forward Iterator • Can be both incremented and decremented • i.e. allows "going back"

  48. Iterators • Random Access Iterator • Refinement of Bidirectional Iterator • Constant-time moving in arbitrarily-sized steps • i.e. can increment/decrement with any value, not just 1 step like other iterators • e.g. increment a random access iterator 5 steps: • Note: using vector iterator, as it is a Random Access Iterator vector<int>::iterator iter = someVector.begin(); iter+=5;

  49. Iterators and Containers • Most container operations require iterators or return iterators • erase(), find(), insert() to name a few • Some containers require iterators • To access elements in a meaningful way • list, set, multiset, multimap • Iterating over maps/sets • Gives the elements in order • Note: Container iterators are at least Forward

  50. Iterators and Containers • Iterating a container • i.e. go through container elements with iterator • Instantiate an iterator of the container's type • Set it to the beginning (usually .begin()) • Start a loop, incrementing the iterator • Stop if the iterator equals .end() of container • end()– iterator pointing "after the last element" • At each step, the iterator will point to an element (unless you've reached end())

More Related