C++ 11 and the Standard Library: Containers, Iterators, Algorithms

Similar documents
C++ Standard Template Library

TDDD38 - Advanced programming in C++

Lesson 13 - Vectors Dynamic Data Storage

CSE 100: C++ TEMPLATES AND ITERATORS

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11

STL: C++ Standard Library

Dynamic Data Structures

CSE 100: C++ TEMPLATES AND ITERATORS

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

COEN244: Class & function templates

CSE 100: C++ TEMPLATES AND ITERATORS

use static size for this buffer

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

Review of Important Topics in CS1600. Functions Arrays C-strings

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Pointers, Dynamic Data, and Reference Types

Summary. Design. Layout

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Introducing C++ to Java Programmers

Advanced C++ STL. Tony Wong

CSI33 Data Structures

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials)

Vector and Free Store (Vectors and Arrays)

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Tree traversals and binary trees

Vector and Free Store (Pointers and Memory Allocation)

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

STL Quick Reference for CS 241

ECE 250 Algorithms and Data Structures

Delhi Noida Bhopal Hyderabad Jaipur Lucknow Indore Pune Bhubaneswar Kolkata Patna Web: Ph:

CSCE 2014 Final Exam Spring Version A

Midterm Review. PIC 10B Spring 2018

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

THINK LIKE CREATIVE PROBLEM SOLVING V. ANTON SPRAUL

Chapter 5. The Standard Template Library.

Tutorial 6. Y. Bernat. Object Oriented Programming 2, Spring Y. Bernat Tutorial 6

Introduction to C++ Introduction to C++ 1

Priority Queues and Huffman Trees

Introduction to Core C++

Abstract Data Types 1

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Standard Template Library

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

C Pointers. 6th April 2017 Giulio Picierro

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)

04-19 Discussion Notes

Intermediate Programming, Spring 2017*

Linked lists. Comp Sci 1575 Data Structures. Definitions. Memory structure. Implementation. Operations. Comparison

CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010

7 TEMPLATES AND STL. 7.1 Function Templates

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Consider the program...

Abstract Data Types 1

Templating functions. Comp Sci 1570 Introduction to C++ Administrative notes. Review. Templates. Compiler processing. Functions Overloading

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012

Templates and Vectors

Run Time Environment

15. Pointers, Algorithms, Iterators and Containers II

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists

Lecture 2: C Programm

Algorithms and Data Structures

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Chapter 15 - C++ As A "Better C"

The Standard Template Library. An introduction

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Tokens, Expressions and Control Structures

CIS 190: C/C++ Programming. Lecture 12 Student Choice

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

CSE 307: Principles of Programming Languages

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

Computational Physics

1 Short Answer (7 Points Each)

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

Lecture on pointers, references, and arrays and vectors

This is a set of practice questions for the final for CS16. The actual exam will consist of problems that are quite similar to those you have

Short Notes of CS201

CSE030 Fall 2012 Final Exam Friday, December 14, PM

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

LECTURE 11 TREE TRAVERSALS

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

Pointers (continued), arrays and strings

C++ Programming Chapter 7 Pointers

CS201 - Introduction to Programming Glossary By

Data Structures Question Bank Multiple Choice

17. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d!

Transcription:

and the Standard Library:,, Comp Sci 1575

Outline 1 2 3 4

Outline 1 2 3 4

#i n clude <i o s t r e a m > i n t main ( ) { i n t v a l u e 0 = 5 ; // C++ 98 i n t v a l u e 1 ( 5 ) ; // C++ 98 i n t v a l u e {5}; // s t d : : s t r i n g a{ h e l l o } ; // i n t v a l u e ; // C++ 98 // v a l u e ( ) // l o o k s l i k e a f u n c t i o n, e r r o r i n t v a l u e 2 { } ; // d e f a u l t to 0 ; i n t i = 3. 9 9 ; // i g e t s 3 ; no warning / e r r o r i n t k { 3. 9 9 } ; // i g e t s 3 ; warning } return 0 ;

with arrays #i n clude <i o s t r e a m > i n t main ( ) { // C++ 98 i n t a r r [ ] = { 1, 2, 3, 4, 5 } ; } // o p t i o n a l i n t a r r [ ] { 1, 2, 3, 4, 5 } ; return 0 ; This is consistent with non-arrays now.

Outline 1 2 3 4

loops #i n clude <i o s t r e a m > i n t main ( ) { i n t f i b o n a c c i [ ] = {0, 1, 1, 2, 3, 5, 8 } ; f o r ( i n t number : f i b o n a c c i ) s t d : : cout << number <<, ; } return 0 ;

loops: modify element #i n clude <i o s t r e a m > i n t main ( ) { i n t f i b p l u s [ ] = {0, 1, 1, 2, 3, 5, 8 } ; f o r ( i n t &number : f i b p l u s ) number++; f o r ( i n t number : f i b p l u s ) s t d : : cout << number <<, ; } return 0 ;

Fast and safe loops #i n clude <i o s t r e a m > i n t main ( ) { i n t f i b o n a c c i [ ] = {0, 1, 1, 2, 3, 5, 8 } ; f o r ( const i n t &number : f i b o n a c c i ) s t d : : cout << number <<, ; } return 0 ; Avoid copy

Outline 1 2 3 4

type deduction #i n clude <i o s t r e a m > i n t add ( i n t x, i n t y ) { return x + y ; } i n t main ( ) { d = 5. 0 ; // 5. 0 i s a double l i t e r a l i = 1 + 2 ; // e v a l u a t e s to an i n t e g e r sum = add ( 5, 6 ) ; // add ( ) r e t u r n s i n t } return 0 ;

in loops #i n clude <i o s t r e a m > i n t main ( ) { f i b o n a c c i [ ] = {0, 1, 1, 2, 3, 5, 8 } ; f o r ( number : f i b o n a c c i ) s t d : : cout << number <<, ; } return 0 ; Warning: For-each doesn t work with pointers to an array, and thus with arrays passed to functions.

Outline 1 2 3 4

should generally be used instead of NULL NULL is a manifest constant (a #define of C) that s actually an integer that can be assigned to a pointer because of an implicit conversion. is a keyword representing a value of self-defined type, that can convert into a pointer, but not into integers. #i n clude <i o s t r e a m > i n t main ( ) { i n t i = NULL ; // OK // i n t i = n u l l p t r ; // e r r o r, no c o n v e r t to i n t i n t p = NULL ; //ok, i n t c o n v e r t e d i n t o p t r i n t p = n u l l p t r ; // ok // suppose you have two f u n c t i o n s i n o v e r l o a d : void func ( i n t x ) ; void func ( i n t x ) ; } Now, if you call func(null), you are actually calling the int variant, NULL being an int. But func() will call the pointer variant, not being an int.

Outline 1 2 3 4

structures Color key:

Sorting algorithms

Outline 1 2 3 4

Outline 1 2 3 4

is now just part of standard namespace Old diagram of the Standard Template Library ()

Main pillars of the manage storage space for elements and provide member functions to access them. Implemented as templated classes, with flexibility of types as elements. act on containers, and perform operations like, sorting, searching, and transforming of the contents of the aforementioned containers. step through elements of collections of objects in containers or subsets of containers. Pointer-like iterators can traverse many container classes in modularly.

Example std :: vector Check out the code: container with iterators and algorithms A dynamic C-like array (i.e., capable of random access) with the ability to resize itself matically when inserting or erasing an object. Random access is done in constant, O(1) time. Insertion or removal of elements at the back takes average time O(1), amortized constant time. Removing the last element takes only constant time, because no re-sizing happens. Insertion or removal of elements at the beginning or middle is linear in distance to the end of the vector O(n). See: Intro vector.cpp

Outline 1 2 3 4

library is a generic collection of class templates and algorithms that allow programmers to easily implement common data structures like queues, lists, and stacks. Classes of containers, each of which is designed to support a different set of operations: 1 sequence containers 2 associative containers 3 un-ordered associative containers 4 container adaptors (modify above) manage storage space that is allocated for their elements and provides member functions to access them, either directly or through iterators (objects with properties similar to pointers). The set of containers have at least several member functions in common with each other, and share functionalities.

For a comprehensive list, see: http://en.cppreference.com/w/cpp/container http://www.cplusplus.com/reference/stl/ https://en.wikipedia.org/wiki/standard_ Template_Library

Simple utilities: pair, tuple Not in the but Utilities http://en.cppreference.com/w/cpp/utility/pair http://en.cppreference.com/w/cpp/utility/tuple

How to choose your container?

Outline 1 2 3 4

An iterator can be imagined as a pointer to a given element in the container, with overloaded operators to provide a subset of well-defined functions normally provided by pointers: Operator* Dereferencing the iterator returns the element that the iterator is currently pointing at. Operator++ Moves the iterator to the next element in the container. Most iterators also provide Operator to move to the previous element. Operator== and Operator!= Basic comparison operators to determine if two iterators point to the same element. To compare the values that two iterators are pointing at, dereference the iterators first, and then use a comparison operator. Operator= Assign the iterator to a new position (typically the start or end of the container s elements). To assign the value of the element the iterator is point at, dereference the iterator first, then use the assign operator.

Where does forward list go? http://en.cppreference.com/w/cpp/iterator http://www.cplusplus.com/reference/iterator/

Each category of iterator is defined by the operations that can be performed on it. Any type that supports the necessary operations can be used as an iterator, e.g., pointers support all of the operations required by RandomAccessIterator, so pointers can be used anywhere a RandomAccessIterator is expected.

Each container includes at least 4 member functions for the operator= to set the values of named LHS iterators. begin() returns an iterator to the first element. end() returns an iterator one past the last element. cbegin() returns a const (read-only) iterator to the first element. cend() returns a const (read-only) iterator one past the last element. end() doesn t point to the last element in the list. This makes looping easy: iterating over the elements can continue until the iterator reaches end(), and then you know you re done.

iterator example #i n c l u d e <i o s t r e a m> #i n c l u d e <v e c t o r> #i n c l u d e <str ing > i n t main ( ) { s t d : : v e c t o r<i n t> i n t s {1, 2, 4, 8, 16}; s t d : : v e c t o r<s t d : : s t r i n g > f r u i t s { orange, a p p l e, r a s p b e r r y }; std : : vector<char> empty ; // Sums a l l i n t e g e r s i n t h e v e c t o r i n t s ( i f any ), p r i n t i n g o n l y t h e r e s u l t. i n t sum = 0 ; f o r ( i t = i n t s. c b e g i n ( ) ; i t!= i n t s. cend ( ) ; i t ++) sum += i t ; s t d : : cout << Sum o f i n t s : << sum << \n ; // P r i n t s t h e f i r s t f r u i t i n t h e v e c t o r f r u i t s, w i t h o u t c h e c k i n g s t d : : cout << F i r s t f r u i t : << f r u i t s. b e g i n ( ) << \n ; // c h e c k s cout << empty. empty ( ) ; i f ( empty. b e g i n ( ) == empty. end ( ) ) s t d : : cout << v e c t o r empty i s i n d e e d empty.\ n ; } // A l t e r n a t i v e s y n t a x i t 1 = i n t s. b e g i n ( ) ; i t 2 = s t d : : b e g i n ( i n t s ) ;

Container have different iterator invalidation rules Each container has different rules for when an iterator will be invalidated after operations on the container: http://en.cppreference.com/w/cpp/container

Outline 1 2 3 4

: example of heap functions Defines functions for a variety of purposes (e.g. searching, sorting, counting, manipulating) that operate on ranges of elements. Range is defined as [first, last) where last refers to the element past the last element to inspect or modify. http://en.cppreference.com/w/cpp/algorithm/ http://www.cplusplus.com/reference/algorithm/ For example, heap operations can be performed on a vector: is heap checks if the given range is a max heap is heap until finds the largest subrange that is a max heap make heap creates a max heap out of a range of elements push heap adds last-1 element to a max heap pop heap removes the largest element from a max heap by moving to end sort heap turns a max heap into a range of elements sorted in ascending order

: example of heap functions See: Heap algorithms.cpp How can we do this more directly?

Outline 1 2 3 4

std::priority queue #include < queue > Priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction. User-provided Compare can be supplied to change the ordering, e.g., using std::greater< T > would cause the smallest element to appear as the top(). Working with a priority queue is similar to managing a heap in some random access container, with the benefit of not being able to accidentally invalidate the heap.

std::priority queue template parameters template< c l a s s T, c l a s s C o n t a i n e r = s t d : : v e c t o r <T>, c l a s s Compare = s t d : : l e s s <typename C o n t a i n e r : : v a l u e t y p e > > T - The type of the stored elements. The behavior is undefined if T is not the same type as Container::value type. Container - Type of underlying container to store the elements. Container must satisfy requirements of SequenceContainer, and its iterators must satisfy the requirements of RandomAccessIterator. It must provide the following functions with the usual semantics: front(); push back(); pop back(); Standard containers std::vector and std::deque satisfy these requirements. Compare - type providing a strict weak ordering.

Demo code: priority queue See: Priority queue.cpp