13.2 the standard template library (stl)

48
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo, Ontario, Canada ece.uwaterloo.ca [email protected] © 2006-2013 by Douglas Wilhelm Harder. Some rights reserved. 13.2 The Standard Template Library (STL)

Upload: reba

Post on 23-Feb-2016

55 views

Category:

Documents


0 download

DESCRIPTION

13.2 The Standard Template Library (STL). Outline. In this topic, we will look at linked lists The Node and List classes Accessors and mutators The implementation of various member functions Stepping through a linked list Defining the copy and assignment operator - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 13.2 The Standard Template Library (STL)

ECE 250 Algorithms and Data Structures

Douglas Wilhelm Harder, M.Math. LELDepartment of Electrical and Computer EngineeringUniversity of WaterlooWaterloo, Ontario, Canada

[email protected]

© 2006-2013 by Douglas Wilhelm Harder. Some rights reserved.

13.2 The Standard Template Library (STL)

Page 2: 13.2 The Standard Template Library (STL)

2Standard Template Library

Outline

In this topic, we will look at linked lists– The Node and List classes– Accessors and mutators– The implementation of various member functions– Stepping through a linked list– Defining the copy and assignment operator– Defining move constructors and move assignment operators– Discussed efficiencies

Page 3: 13.2 The Standard Template Library (STL)

3Standard Template Library

Arrays

The Standard Template Library has three variations on arrays:template < typename T, size_t N >class array;

template < typename T, class Alloc = allocator<T> >

class vector;

template < size_t N >class bitset;

Page 4: 13.2 The Standard Template Library (STL)

4Standard Template Library

array<T, N>

This is a sequence container with a linear order– Elements are accessed by their position

The memory allocation is contiguous– Random access is Q(1)

The memory is allocated at compile time

Page 5: 13.2 The Standard Template Library (STL)

5Standard Template Library

array<T, N>

To make return types more standard, the C++ STL defines specific member types associated with each class:

array<T, N>::value_type Tarray<T, N>::reference T &array<T, N>::const_referenceT const &array<T, N>::pointerT *array<T, N>::const_pointer T

const *array<T, N>::iteratorarray<T, N>::const_iteratorarray<T, N>::reverse_iteratorarray<T, N>::const_reverse_iteratorarray<T, N>::size_type size_tarray<T, N>::difference_type

ptrdiff_t

Page 6: 13.2 The Standard Template Library (STL)

6Standard Template Library

array<T, N>

Member functions include:– The eight iterators

begin end rbegin rend cbegin cend crbegin crend

iterator begin() noexcept;const_iterator begin() const noexcept;const_iterator cbegin() const noexcept;

– Capacityconstexpr size_type size() noexcept;constexpr size_type max_size() noexcept;constexpr bool empty() noexcept;

Page 7: 13.2 The Standard Template Library (STL)

7Standard Template Library

array<T, N>

Member functions include:– Element access

reference operator[]( size_type );const_reference operator[]( size_type ) const;

reference at( size_type );const_reference at ( size_type ) const;

reference front();const_reference front() const;reference back();const_reference back() const;

pointer data() noexcept;const_pointer data() const noexcept;

Page 8: 13.2 The Standard Template Library (STL)

8Standard Template Library

array<T, N>

Member functions include:– Modifiers

void fill( const_reference );void swap( array & ) noexcept( ... );

Page 9: 13.2 The Standard Template Library (STL)

9Standard Template Library

array<T, N>

Example:#include <array>

int main() { std::array<int, 5> v;

for ( int i = 0; i < 5; ++i ) { v[i] = i; }

for ( auto itr = v.begin(); itr != v.end(); ++itr ) { *itr = (*itr)^2; }

v.fill( 7 ); int *ptr = v.data();

return 0;}

Page 10: 13.2 The Standard Template Library (STL)

10Standard Template Library

bitset<N>

Page 11: 13.2 The Standard Template Library (STL)

11Standard Template Library

vector<T>

This is a sequence container with a linear order– Elements are accessed by their position

The memory allocation is contiguous– Random access is Q(1)

The array allocation is dynamic– The size of the array can change at runtime

The user can specify the method of allocation

Page 12: 13.2 The Standard Template Library (STL)

12Standard Template Library

vector<T>

To make return types more standard, the C++ STL defines specific member types associated with each class:

vector<T>::value_type Tvector<T>::reference T &vector<T>::const_reference T const &vector<T>::pointer T *vector<T>::const_pointer T const *vector<T>::iteratorvector<T>::const_iteratorvector<T>::reverse_iteratorvector<T>::const_reverse_iteratorvector<T>::allocator_type

allocate<value_type>vector<T>::size_type size_tvector<T>::difference_type ptrdiff_t

Page 13: 13.2 The Standard Template Library (STL)

13Standard Template Library

vector<T>

Member functions include:– Constructors

explicit vector();explicit vector( size_type );vector( size_type, const_reference );

template < class InputIterator >vector( InputIterator first, InputIterator last );

vector( vector const & );vector( vector && );

vector( initializer_list<value_type> );

Page 14: 13.2 The Standard Template Library (STL)

14Standard Template Library

vector<T>

Member functions include:– Assignment operator

vector &operator=( vector const & );vector &operator=( vector && );vector &operator=( initializer_list<value_type> );

– The last lets us:std::vector<int> v(10);v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Page 15: 13.2 The Standard Template Library (STL)

15Standard Template Library

vector<T>

Member functions include:– The eight iterators

begin end rbegin rend cbegin cend crbegin crend

– Each has the various signatures:iterator begin() noexcept;const_iterator begin() const noexcept;const_iterator cbegin() const noexcept;

Page 16: 13.2 The Standard Template Library (STL)

16Standard Template Library

vector<T>

Member functions include:– Capacity

size_type size() const noexcept;size_type capacity() const noexcept;size_type maxsize() const noexcept;void resize( size_type );void resize( size_type, const_reference );bool empty() const noexcept;bool empty() const noexcept;void reserve( size_type );void shrink_to_fit();

Page 17: 13.2 The Standard Template Library (STL)

17Standard Template Library

vector<T>

Member functions include:– Element access

reference operator[]( size_type );const_reference operator[]( size_type ) const;

reference at( size_type );const_reference at ( size_type ) const;

reference front();const_reference front() const;reference back();const_reference back() const;

pointer data() noexcept;const_pointer data() const noexcept;

Page 18: 13.2 The Standard Template Library (STL)

18Standard Template Library

vector<T>

Member functions include:– Modifiers

template < class Iterator > void assign( Iterator, Iterator );

void assign( size_type, const_reference );void assign( initializer_list<value_type> );

void push_back( const_reference );void push_back( value_type&& );void pop_back();

Page 19: 13.2 The Standard Template Library (STL)

19Standard Template Library

vector<T>

Member functions include:– Modifiers

iterator insert( const_iterator position, const_reference );iterator insert( const_iterator position, size_type n, const_reference );

template < class Iterator >iterator insert( const_iterator position, Iterator first, Iterator last );

iterator insert( const_iterator position, value_type&& );

iterator insert( const_iterator position, initializer_list<value_type> );

Page 20: 13.2 The Standard Template Library (STL)

20Standard Template Library

vector<T>

Member functions include:– Allocator

allocator_type get_allocator() const noexcept;

– Non-member function overloadstemplate < typename T >void swap( vector<T> &, vector<T> & );

template < typename T >bool operator==( const vector<T> &, const

vector<T> & );

• Includes the relational operators !=, <, <=, >, and >=• Uses a lexicographical comparison

Page 21: 13.2 The Standard Template Library (STL)

21Standard Template Library

vector<bool>

One specialization of vector is for Boolean values:– Normally, each bool occupies one byte– Reasonable specializations of vector<bool> use one bit per entry– One new function:

void flip() noexcept;– A mechanism for referencing individual bits and interpreting them as

type bool

Page 22: 13.2 The Standard Template Library (STL)

22Standard Template Library

vector<T, Alloc>

One thing that has been overlooked is: how is memory allocated?

By default, memory allocation is performed using new[] and delete[]– What if this is too slow or inappropriate for a particular use of vector?

The actual class definition is:template < typename T, class Alloc =

allocator<T> >class vector;

Page 23: 13.2 The Standard Template Library (STL)

23Standard Template Library

vector<T, Alloc>

An allocator class must have specific member types and functions:

template <class T>class Allocator { public: typedef T value_type; typedef T * pointer; typedef const T * const_pointer; typedef T & reference; typedef const T & const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef propagate_on_container_move_assignment true_type;

template <class U> struct rebind { typedef Allocator<U> other; };

Page 24: 13.2 The Standard Template Library (STL)

24Standard Template Library

vector<T, Alloc>

allocator() nothrow; allocator ( const allocator & ) nothrow;

template <class U> allocator( const allocator<U> & ) nothrow;

~allocator() throw;

pointer address( reference ) const noexcept; const_pointer address( const_reference ) const noexcept;

pointer allocate( size_type, allocator<void>::const_pointer = 0 ); void deallocate( pointer, size_type );

size_type max_size() const nothrow;

template <class U, class... Args> void construct( U* p, Args&&... args );

template <class U> void destroy ( U* p );};

Page 25: 13.2 The Standard Template Library (STL)

25Standard Template Library

vector<T, Alloc>

Why would you want a different allocator?– Suppose you want persistent memory allocation—allocation that

continues from one execution of a program to the next– Intel’s thread building blocks improve the performance of multithreaded

applications by usingstd::vector< T, tbb::scalable_allocator<T> >

– Electronic Arts has a STL optimized for gaming software—memory tends to be more restrictive on gaming platforms

– Tracking allocations and deallocations for debugging or efficiency– Suppose you want to use memory-mapped files—addresses in memory

that are mapped not to RAM but to virtual memory

http://stackoverflow.com/questions/826569/compelling-examples-of-custom-c-stl-allocators

From the point of view of portability, all the machine-specific things which relate to the notion of address, pointer, and so on, are encapsulated within a tiny, well-understood mechanism.

Alex Stepanov, designer of the STL

Page 26: 13.2 The Standard Template Library (STL)

26Standard Template Library

Linked Lists

The Standard Template Library has two variations on a linked list:template < typename T, class Alloc =

allocator<T> >class list;

template < typename T, class Alloc = allocator<T> >

class forward_list;

Page 27: 13.2 The Standard Template Library (STL)

27Standard Template Library

Stacks, Queues, and Deques

The Standard Template Library has all three classes:template < typename T, class Alloc =

allocator<T> >class deque;

template < typename T, class Container = deque<T> >

class stack;

template < typename T, class Container = deque<T> >

class queue;

Page 28: 13.2 The Standard Template Library (STL)

28Standard Template Library

Weakly Ordered Containers

Four containers are based on weak linear orderings:template < typename Key, class Compare = less<Key>, class Alloc = allocator<Key>> class set;

template < typename Key, class Compare = less<Key>, class Alloc = allocator<Key>> class multiset;

Page 29: 13.2 The Standard Template Library (STL)

29Standard Template Library

Weakly Ordered Containers

Four containers are based on weak linear orderings:template < typename Key, typename T, class Compare = less<Key>, class Alloc = allocator< pair<const

Key, T> >> class map;

template < typename Key, typename T, class Compare = less<Key>,

class Alloc = allocator< pair<const Key, T> >

> class multimap;

Page 30: 13.2 The Standard Template Library (STL)

30Standard Template Library

Weakly Ordered Containers

What’s the difference?– A simple container stores objects– An associative containers stores an object related to a key were

accesses are performed using the key– A weak ordering is a linear ordering of equivalence classes

• With linear orderings, either a < b, a = b, or a > b• With weak orderings, either a < b, a ~ b, or a > b• That is, if a is neither less than or greater than b, it is equivalent to b• Example: people compared using their age in years

– The container may store either• Only a single item per equivalence class, or• Multiple items per equivalence class

Page 31: 13.2 The Standard Template Library (STL)

31Standard Template Library

Weakly Ordered Containers

Which are which?

The class definitions:– The class definitions for set and multiset are the same– map and multimap are similar with:

• Two additional member functions for access via the keys• Arguments for searching are based on keys• Returns are based on what is being associated with the key

Items per equivalence class Simple Container Associative ContainerAt most one set mapAn arbitrary number multiset multimap

Page 32: 13.2 The Standard Template Library (STL)

32Standard Template Library

set<Key>

To make return types more standard, the C++ STL defines specific member types associated with each class:

set<Key>::key_type Keyset<Key>::value_typeKeyset<Key>::reference Key &set<Key>::const_reference Key

const &set<Key>::pointer Key *set<Key>::const_pointer Key

const *set<Key>::iteratorset<Key>::const_iteratorset<Key>::reverse_iteratorset<Key>::const_reverse_iteratorset<Key>::size_type size_tset<Key>::difference_type

ptrdiff_t

Page 33: 13.2 The Standard Template Library (STL)

33Standard Template Library

Priority Queues

The Standard Template Library has a priority queue classes:template < typename T, class Container = vector<T>, class Compare

= less< typename Container::value_type> >

class priority_queue;

Page 34: 13.2 The Standard Template Library (STL)

34Standard Template Library

Hashed Containers

For containers are based on hashing:template < typename Key, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<Key>> class unordered_set;

template < typename Key, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<Key>> class unordered_multiset;

Page 35: 13.2 The Standard Template Library (STL)

35Standard Template Library

Hashed Containers

For containers are based on hashing:template < typename Key, typename T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator< pair<const

Key, T> >> class unordered_set;

template < typename Key, typename T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator< pair<const

Key, T> >> class unordered_multiset;

Page 36: 13.2 The Standard Template Library (STL)

36Standard Template Library

unordered_set<Key>

This is a simple container with unordered elements– Random access is Q(1)

The elements stored are uniqueThe user can specify the method of allocation

Page 37: 13.2 The Standard Template Library (STL)

37Standard Template Library

unordered_set<Key>

To make return types more standard, the C++ STL defines specific member types associated with each class:

key_type Keyvalue_type Keyhasher hash<Key>key_equal equal_to<Key>reference Key &const_reference Key const &pointer Key *const_pointer Key const *iteratorconst_iteratorlocal_iteratorconst_local_iteratorallocator_type

allocate<value_type>size_type size_tdifference_type ptrdiff_t

Page 38: 13.2 The Standard Template Library (STL)

38Standard Template Library

unordered_set<Key>

Member functions include:– Constructors

explicit unordered_set( size_type, const hasher & = hasher(), const key_equal & = key_equal(), const allocator_type & = allocator_type() );

unordered_set( unordered_set const & );unordered_set( unordered_set && );

template <class InputIterator>unordered_set( InputIterator first, InputInterator last, ... );

unordered_set( initializer_list<value_type>, ... );

Page 39: 13.2 The Standard Template Library (STL)

39Standard Template Library

unordered_set<Key>

Member functions include:– Assignment operator

unordered_set &operator=( unordered_set const & );unordered_set &operator=( unordered_set && );unordered_set &operator=( initializer_list<value_type> );

Page 40: 13.2 The Standard Template Library (STL)

40Standard Template Library

unordered_set<Key>

Member functions include:– The four forward iterators

begin end cbegin cend

– Each has the various signatures:iterator begin() noexcept;const_iterator begin() const noexcept;local_iterator begin( size_type );const_local_iterator begin( size_type ) const;

Page 41: 13.2 The Standard Template Library (STL)

41Standard Template Library

unordered_set<Key>

Member functions include:– Capacity

size_type size() const noexcept;size_type maxsize() const noexcept;bool empty() const noexcept;

Page 42: 13.2 The Standard Template Library (STL)

42Standard Template Library

unordered_set<Key>

Member functions include:– Element lookup

iterator find( const key_type & );const_iterator find( const key_type & ) const;

size_type count( const key_type & );

pair<iterator,iterator> equal_range( const key_type & );

pair<const_iterator,const_iterator> equal_range( const key_type & ) const;

Page 43: 13.2 The Standard Template Library (STL)

43Standard Template Library

unordered_set<Key>

Member functions include:– Modifiers

template <class... Args> iterator emplace( Args&&... );

template <class... Args>iterator emplace_hint( const_iterator,

Args&&... );

pair<iterator,bool> insert( reference& );pair<iterator,bool> insert( value_type && );

pair<iterator,bool> insert( const_iterator, reference& );

pair<iterator,bool> insert( const_iterator, value_type && );

Page 44: 13.2 The Standard Template Library (STL)

44Standard Template Library

unordered_set<Key>

Member functions include:– Modifiers

iterator erase( const_iterator position );iterator erase( reference );iterator insert( const_iterator, const_iterator );

void clear() noexcept;

void swap( unordered_set & );

Page 45: 13.2 The Standard Template Library (STL)

45Standard Template Library

unordered_set<Key>

Member functions include:– Allocator

allocator_type get_allocator() const noexcept;

– Non-member function overloadstemplate < typename T >void swap( vector<T> &, vector<T> & );

template < typename T >bool operator==( const vector<T> &, const

vector<T> & );

• Includes the relational operators !=, <, <=, >, and >=• Uses a lexicographical comparison

Page 46: 13.2 The Standard Template Library (STL)

46Standard Template Library

Summary

Data Structure STL ContainersArray array<T, N> bitset<N>

vector<T, A> vector<bool, A>Linked lists forward_list<T, A>

list<T, A>Stacks, etc. stack<T, D> queue<T, D>

deque<T, A>Weakly ordered set<K, C, A> multiset<K, C, A>

map<K, T, C, A> multimap<K, T, C, A>Priority queue propority_queue<T, V>Hash tables unordered_set<T, H, P, A> unordered_mulitset<T, H, P, A>

unordered_map<K, T, H, P, A>

unordered_mulitmap<K, T, H, P, A>

Page 47: 13.2 The Standard Template Library (STL)

47Standard Template Library

Summary

We have looked at all the containers implemented in the STL– These cover all data structures looked at in this class– The most recent additions were singly linked lists and hash tables

Page 48: 13.2 The Standard Template Library (STL)

48Standard Template Library

References

Donald E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd Ed., Addison Wesley, 1998, §5.4, pp.248-379.

Wikipedia, https://en.wikipedia.org/wiki/Linked_list http://stackoverflow.com/error?aspxerrorpath=/questions/8848363/rvalue-reference-with-assignement-operator

These slides are provided for the ECE 250 Algorithms and Data Structures course. The material in it reflects Douglas W. Harder’s best judgment in light of the information available to him at the time of preparation. Any reliance on these course slides by any party for any other purpose are the responsibility of such parties. Douglas W. Harder accepts no responsibility for damages, if any, suffered by any party as a result of decisions made or actions based on these course slides for any other purpose than that for which it was intended.