+ All Categories
Home > Documents > Advanced STL

Advanced STL

Date post: 24-Feb-2016
Category:
Upload: aviv
View: 75 times
Download: 0 times
Share this document with a friend
Description:
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 - PowerPoint PPT Presentation
Popular Tags:
92
Advanced STL Overview of Containers, Iterators, Algorithms. Using Functionality in STL Learning & Development Team http://academy.telerik.com Telerik Software Academy
Transcript
Page 1: Advanced STL

Advanced STLOverview of Containers, Iterators,

Algorithms. Using Functionality in STL

Learning & Development Teamhttp://academy.telerik.com

Telerik Software Academy

Page 2: Advanced STL

Table of Contents (1)1. Containers

1.Concepts2.Priority queue3.(multi)Sets, (multi)Maps

2. Iterators1.Concepts2.STL container iterators3.Insertion iterators and iterators on

streams2

Page 3: Advanced STL

Table of Contents (2)3. Algorithms

3. Heap creation4. Sorting, Operations on sorted

containers5. Searching6. Combinatorial

4. Functors3. Concepts4. Creating and using Generators,

Unary and Binary Functors

Page 4: Advanced STL

ContainersSTL Container Architecture, Advanced

Containers

Page 5: Advanced STL

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

Page 6: Advanced STL

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

Page 7: Advanced STL

Containers – Pseudo-Diagram

Container

Forward, Reversible, Random Access

SequenceFront/Back Insertion

Associative ContainerSimple, Pair, Sorted,

Uniquevecto

rlist

dequebit_vectorset

map

multiset

multimap

stackqueuepriority_que

ue

Adaptor

Page 8: Advanced STL

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.

Page 9: Advanced STL

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

Page 10: Advanced STL

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

Page 11: Advanced STL

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

Page 12: Advanced STL

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)

Page 13: Advanced STL

Container Adaptors Adaptors limit access to containers

Fundamental for FIFO and LIFO data structures

Adaptor models: queue stack priority_queue

Page 14: Advanced STL

Advanced Container Modelspriority_queue, map, set, multimap,

multiset, Usage and Examples

Note: for basic container models, see Basic ADTs in STL

Page 15: Advanced STL

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

Page 16: Advanced STL

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)

16

Page 17: Advanced STL

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"

Page 18: Advanced STL

Priority Queue UsageLive Demo

Page 19: Advanced STL

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

Page 20: Advanced STL

Simple Problem Solved with a Priority Queue

Live Demo

Page 21: Advanced STL

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

Page 22: Advanced STL

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

Page 23: Advanced STL

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

23

Page 24: Advanced STL

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

Page 25: Advanced STL

Set UsageLive Demo

Page 26: Advanced STL

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

Page 27: Advanced STL

Simple Problem Solved with a Set

Live Demo

Page 28: Advanced STL

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

Page 29: Advanced STL

Multiset UsageLive Demo

Page 30: Advanced STL

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

Page 31: Advanced STL

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

Page 32: Advanced STL

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.erase("Joro");

peopleAges["Petya"];peopleAges["Petya"]++;

Page 33: Advanced STL

Map UsageLive Demo

Page 34: Advanced STL

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.

Page 35: Advanced STL

Simple Problem Solved with a Map

Live Demo

Page 36: Advanced STL

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

Page 37: Advanced STL

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"));

Page 38: Advanced STL

Multimap UsageLive Demo

Page 39: Advanced STL

IteratorsThe Way of STL Element Access

Page 40: Advanced STL

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

Page 41: Advanced STL

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;

Page 42: Advanced STL

Iterators: Simple ExampleLive Demo

Page 43: Advanced STL

Iterators and ContainersSyntax, Usage, Examples

Page 44: Advanced STL

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…

Page 45: Advanced STL

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

Page 46: Advanced STL

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"

Page 47: Advanced STL

Iterators Bidirectional Iterator

Refinement of Forward Iterator Can be both incremented and

decremented i.e. allows "going back"

Page 48: Advanced STL

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;

Page 49: Advanced STL

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

Page 50: Advanced STL

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

Page 51: Advanced STL

Iterators and Containers

Iterating a set<string> Result: strings in lexicographical

order set<string> orderedStrings;

orderedStrings.insert(...);...

for(set<string>::iterator iter = orderedStrings.begin(); stringsIter != orderedStrings.end(); stringsIter++){ cout<<(*stringsIter)<<endl;}

Page 52: Advanced STL

Iterating Over ContainersLive Demo

Page 53: Advanced STL

Iterators and Containers

Don't overuse iterators Especially for Random Access

Containers vector and deque support the [] operator For both, [] does fast pointer

arithmetic Faster to traverse by index, than by

iterator

Page 54: Advanced STL

Iterators and Containers

Iterators are the standard link between data structures and algorithms in STL Some algorithms will return results

by iterator You will have to iterate the results

The power of iterators: Separate containers from

algorithms Any algorithm can work on any

container But they don't need to know about

each other As long as both understand iterators

Page 55: Advanced STL

Iterators and Containers

Simple problem: You are given a sentence and a word contained in that sentence. Show the positions at which the

word is (first word is position 0, second position 1, etc.)

Page 56: Advanced STL

Using Iterators to Take Advantage of

Container OperationsLive Demo

Page 57: Advanced STL

Insertion & Stream Iteratorsostream/istream iterators, front/back

insertion

Page 58: Advanced STL

Insertion & Stream Iterators

STL has built-in iterators for input/output Input & Output iterator

implementations #include<iterator>

Stream iterators Provide formatted read/write access

to streams ostream_iterator, istream_iterator

Insertion iterators (Output iterators) Attach to Sequences and insert

when written to insertion_iterator, front_insertion_iterator, back_insertion_iterator,

Page 59: Advanced STL

Insertion & Stream Iterators

ostream_iterator<T, …> T is the data type to write to the

stream Other template parameters:

info here Initializing with a stream and

output separator:

Writing values

ostream_iterator<int> coutIterator(cout, ", ");

*coutIterator = 5; //equivalent to cout<<5<<", "; //stream advances to next position

Page 60: Advanced STL

ostream_iterator Basic Usage

Live Demo

Page 61: Advanced STL

Insertion & Stream Iterators

istream_iterator<T, …> Initializing with a stream:

Initializing without a stream creates an "End of Stream" iterator

type

Reading (and printing) values to end of stream

stringstream ss; ss.str("5 2 3");istream_iterator<int> ssIterator(ss);

istream_iterator<int> intEOS;

while(ssIterator != intEOS){ cout<<(*ssIterator)<<" "; //getting current value ssIterator++; //advance to next value}

Page 62: Advanced STL

istream_iterator Basic Usage

Live Demo

Page 63: Advanced STL

Insertion & Stream Iterators

insert_iterator<Container> Container must support insert() Initialize by container instance and

iterator in it

Inserting values is just writing to the element, pointed by the iterator

list<string> words;words.insert("one");words.insert("three");list<string>::iterator wordsMiddle = words.begin();wordsMiddle++;insert_iterator< list<string> >

wordInserter (words, wordsMiddle);

*wordInserter = "hello";

Page 64: Advanced STL

Insertion & Stream Iterators

front_insert_iterator & back_insert_iterator Modifications of insert_iterator Insert only at front/back of a

container Require container to support push_front or push_back, respectively

Initialized by container:list<string> words;front_insert_iterator< list<string> > frontInserter(words);back_insert_iterator< list<string> > backInserter(words);

Page 65: Advanced STL

Insertion Iterators:Basic Usage

Live Demo

Page 66: Advanced STL

Pointers and Iterators Pointers can be implicitly converted to Random Access Iterators Since Random Access iterators use

the same mechanics to move between elements

E.g. algorithms using Random Access Iterators can be executed on arrays You just pass pointers to the

array/elements in the array

Page 67: Advanced STL

Common STL AlgorithmsSorting, Searching, Mutating, Heaps, Combinatorics, etc.

Page 68: Advanced STL

Common STL Algorithms

The STL has a wide range of built-in algorithms, in several categories Non-mutating (searching, counting,

etc.) Mutating (removing, rotating,

swapping, etc.) Sorting Heap operations (make heap, push

heap, etc.) Combinatorial (next/previous

permutation) Set, comparison, numeric, min/max

operations

Page 69: Advanced STL

Common STL Algorithms

Some common principles used by algorithms Algorithms on ranges take them as

iterators In the form [first, last), i.e. last is

non-inclusive Inserting a new element at an

iterator Pushes any existing element at that

iterator forward (i.e. to the next iterator position)

Page 70: Advanced STL

Searching, Counting, Matching

find(first, last, value) Returns 1st iterator, pointing to

same value If no such iterator exists – returns last

count(first, last, value) Returns the number of elements,

equal to value equal(first1, last1, first2)

Checks if the range [first1, last) is element-by-element equal to the range [ first2, first2 + (last1 – first1) )

Page 71: Advanced STL

Searching, Counting, Matching

Live Demo

Page 72: Advanced STL

Mutating Algorithms copy(first, last, result)

Copies the Input Iterator range [first, last)

Into the Output Iterator result fill(first, last, value)

Sets all elements in the range to value

swap_ranges(first, last, first2) Exchanges the range [first1, last)

with the range [first2, first2 + (last1 – first1)) and returns the element after the second range

Page 73: Advanced STL

Mutating AlgorithmsLive Demo

Page 74: Advanced STL

Sorting Algorithms sort(first, last)

Sorts the Random Access Iterator range in ascending order

stable_sort(first, last) Same as sort, but keeps relative

ordering of equal elementsas Potentially a bit slower than sort in

its worst case

Page 75: Advanced STL

Sorting AlgorithmsLive Demo

Page 76: Advanced STL

Heap Operations Note: STL Heaps are what priority_queue uses.

The first/top element is largest, it has 2 child elements which are smaller, they are first/top elements of their own heaps, etc. All STL Heap operations use Random Access Iterators

make_heap(first, last) Makes the range into a heap

push_heap(first, last) Assumes [first, last – 1) is a heap The element at last – 1 is placed in

the heap pop_heap(first, last)

Assumes [first, last) is a heap, removes top

Page 77: Advanced STL

Heap Operations, a.k.a.

How to Make a Priority QueueLive Demo

Page 78: Advanced STL

Combinatorial Algorithms

next_permutation(first, last) Transforms the Bidirectional

Iterator range into the lexicographically next permutation of the elements. If the last permutation has already been reached, transforms into the first permutation (i.e. sorts ascending)

prev_permutation(first, last) Same as next_permutation, but

transforms into the previous permutation

Page 79: Advanced STL

Permutation AlgorithmsLive Demo

Page 80: Advanced STL

FunctorsInjecting Custom Logic Into Containers

and Algorithms

Page 81: Advanced STL

Functors A Function Object (Functor) is anything, which can be called as a function A function is a functor A function pointer is a functor A class/struct, which overloads the () operator

Several Concepts for Functors in STL Generator Unary Function, Predicate Binary Function, Binary Predicate

Page 82: Advanced STL

Functors Generator – called with no arguments

Unary Function – receives a single argument

Binary Function – receives two arguments

Predicate – Unary Function, which returns bool

Binary Predicate – Binary Function, which returns bool

Page 83: Advanced STL

Functor Defining a Binary Predicate for a "greater than" relation As a function:

As a class with operator ()

bool greaterThan(int a, int b){ return a > b;}

struct GreaterThan{ bool operator ()(int a, int b) { return a > b; }}

Page 84: Advanced STL

Functor Advantages to picking the class/struct definition Can keep object state

e.g. count number of comparisons, calculate sum and average of arguments, etc.

Container template parameters need to be types struct/class create types, while

simply taking a function name will give an error

Page 85: Advanced STL

Functors Most containers and algorithms take Functors: Algorithms take Functor objects Containers take Functor types

(template args) Containers and Algorithms

Have default behavior, described by functors

Custom behavior is added through new functors E.g. different ordering rules for a

set/map Or different ordering rules for the

sort algorithm

Page 86: Advanced STL

Functors Example: Using a Functor to order a set's elements in descending orderstruct greaterThan{ bool operator ()(int a, int b) { return a > b; }};int main(){ set<int, greaterThan> nums; nums.insert(...); ... for(set<int>::iterator iter = nums.begin(); iter != nums.end(); iter++) cout<<*iter<<endl; //elements in descending order

Page 87: Advanced STL

Functors: Change Container Ordering

Live Demo

Page 88: Advanced STL

Functors Example: Using a Functor to compare

ranges of doubles by arbitrary epsilon, instead of absolutely:struct EqualEpsilon { double epsilon; EqualEpsilon(double eps) { this->epsilon = eps; } bool operator ()(double a, double b) { return abs(a - b) < this->epsilon; }};int main() { list<double> range1; list<double> range2; //fill values equal(range1.begin(), range1.end(), range2.begin(), EqualEpsilon(0.1)); //will compare by epsilon 0.1}

Page 89: Advanced STL

Functors: Arbitrary Epsilon for Equal

AlgorithmLive Demo

Page 90: Advanced STL

Functors The STL already has a lot of the common required functions defined, e.g.: greater<T> less<T> equal_to<T> and not_equal_to<T> plus<T>, minus<T>, etc. A lot of others – use them for simple

customizations, like changing ordering

Custom Functors can also be used to use sets/maps with your own classes

Page 91: Advanced STL

Examples of Functor Customizations in

the STLLive Demo

Page 92: Advanced STL

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезанияASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET

курсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGapfree C# book, безплатна книга C#, книга Java, книга C# Дончо Минков - сайт за програмиране

Николай Костов - блог за програмиранеC# курс, програмиране, безплатно

?? ? ?

??? ?

?

? ?

??

?

?

? ?

Questions?

?

Advanced STL

http://algoacademy.telerik.com


Recommended