STL Iterators Separating Container from Data Access.

Slides:



Advertisements
Similar presentations
M The University Of Michigan Andrew M. Morgan EECS Lecture 22 Savitch Ch. 16 Intro To Standard Template Library STL Container Classes STL Iterators.
Advertisements

Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Basic C++ Sequential Container Features
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Templates and the STL.
Writing Your Own STL Container Ray Lischner
Data Structures Using C++ 2E
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
C++ Programming Part 2 Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
Lecture 7 : Intro. to STL (Standard Template Library)
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Learning Objective  Standard Template Library.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
More STL Container Classes ECE Last Time Templates –Functions –Classes template void swap_val (VariableType &a, VariableType &b) { VariableType.
Programming in C++ Michal Brabec Petr Malý. Standard Template Library Containers - vector, map, set, deque, list Algorithms - copy, replace, sort, find.
Lecture 7.  There are 2 types of libraries used by standard C++ The C standard library (math.h) and C++ The C++ standard template library  Allows us.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
 2003 Prentice Hall, Inc. All rights reserved vector Sequence Container Declarations –std::vector v; type : int, float, etc. Iterators –std::vector.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Vectors the better arrays. Why Vectors l vectors are implemented as a class (a template to be exact) l they serve the same purpose as arrays but using.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Object-Oriented Programming (OOP) Lecture No. 41
Module 20/21/22: The Standard Template Library
CS212: Object Oriented Analysis and Design
Concepts of Programming Languages
Programming with ANSI C ++
Standard Template Library
Standard Template Library (STL)
Linked lists.
STL Common tools for C++.
C++ Programming Standard Library
Student Book An Introduction
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Friday, February 16, 2018 Announcements… For Today… 4.5-, pgs. 252
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
abstracting away the data structure
Object Oriented Programming COP3330 / CGS5409
Object Oriented Programming COP3330 / CGS5409
Chapter 18: Linked Lists.
Vectors the better arrays.
Constructors and Other Tools
Standard Template Library Model
Doubly Linked List Implementation
Recursive Linked List Operations
The Standard Template Library
STL Containers Some other containers in the STL.
STL Algorithms Examples of how to use some STL algorithms.
Introduction to C++ Linear Linked Lists
Iterators and STL Containers
Lecture 8 : Intro. to STL (Standard Template Library)
STL List.
C++ Templates An Introduction to Generic Programming.
Lesson 25 Miscellaneous Topics
Review of Previous Lesson
Doubly Linked List Implementation
Linked lists.
Vectors the better arrays.
14 – Sequential Containers
STL List.
Presentation transcript:

STL Iterators Separating Container from Data Access

Last Tutorial C++ Templates The Standard Template Library (STL) Function templates (swap, minimum, QuickSort) Class templates (pair) The Standard Template Library (STL) Containers Library – specifically std::vector

Today’s Questions What is an iterator? What operations can I perform on an iterator? What is an std::list? How is an std::list different from an std::vector?

What is an iterator? An iterator identifies an element in a container Similar to a pointer An iterator allows us to access an element in a container Also similar to a pointer An iterator allows us to move between elements in a container Similar to pointer arithmetic An iterator is restricted to efficient operations http://en.cppreference.com/w/cpp/concept/Iterator

Iterator versus operator[] Why not just use array[index] to access elements? operator[] implies random access Random access is not supported by all data structures In the STL, all containers have iterators defined Each of these iterator types are different: std::vector<int>::iterator std::vector<float>::iterator std::list<int>::iterator

std::vector functions Already Covered Today’s New Functions Accessing – operator[] Inserting – push_back() Modifying – operator[] Querying – size() Complexity of all of the above: O(1) Iterating – begin() Returns an iterator to the first element Iterating – end() Returns an iterator to the element following the last element Used for bounds checking http://en.cppreference.com/w/cpp/container/vector

Where is begin and end? … 1 2 3 4 5 n - 1 my_vector.size() = n 1 2 3 4 5 n - 1 my_vector.begin() my_vector.end() Note: one past the end!

Operating on iterators std::vector<int> numbers = {1, 2, 3, 4}; // Case 1 std::vector<int>::iterator it = numbers.begin(); it = 5; // Case 2 it++; // Case 3 it--; // Case 4 int x = *it; // Case 5 it != numbers.end(); // Case 6 it < numbers.end(); // Case 7 *it = 27; // Case 8 it = numbers.begin() + 2; // Case 9 Case Allowed? Explanation 1 Yes Points to the start of vector (1) 2 No 5 is an int, not an iterator 3 Points to the next element (2) 4 Points to the prior element (1) 5 Sets x to the element value 6 Checks if points to valid element 7 Checks if comes before the end 8 Modifies the element at it 9 Points to the third element Should add animated diagram to illustrate iterator_operations.cpp

Looping Through a Vector std::vector<int> numbers = {1, 2, 3, 4}; // using indices for(size_t i = 0; i < numbers.size(); ++i) { std::cout << numbers[i] << " "; } std::cout << "\n"; // using iterators for(std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { std::cout << *it << " "; Declare iterator type Initialize to first element Ensure iterator valid Advance to next element Dereference to get value of the element vector_looping.cpp

Extract the Negative Values of the Vector std::vector<int> extract_negatives(std::vector<int> & integers) { std::vector<int> negatives; for(std::vector<int>::iterator it = integers.begin(); it != integers.end(); ++it) { if(*it < 0) { negatives.push_back(*it); } return negatives; Using iterators, loop over the integers vector and add elements that are negative to the negatives vector. extract_negatives.cpp

Erase the Negative Values of the Vector void remove_negatives(std::vector<int> & integers) { for(std::vector<int>::iterator it = integers.begin(); it != integers.end();) { if(*it < 0) { it = integers.erase(it); } else { it++; } Do not increment it in the for loop statement erase(iterator) will return an iterator to the next element it is incremented if nothing is erased remove_negatives.cpp

What does erase do? *it processed elements unprocessed elements negative elements copied it2 = integers.erase(it); processed elements unprocessed elements *it2

How does erase perform? erase(iterator) Accepts an iterator to the element that should be erased Returns the next iterator in the vector Complexity: O(n) What is the complexity of remove_negatives? Consider a vector that contains all negative values

How does erase perform? erase(iterator) Accepts an iterator to the element that should be erased Returns the next iterator in the vector Complexity: O(n) What is the complexity of remove_negatives? Consider a vector that contains all negative values We loop over n elements Worst case: we erase n times Complexity: O(n2)

std::list is a Doubly Linked List next data previous next data previous next data previous next data previous … head tail Double links (next and previous) allow for bi-directional access Fast insert and erase Only need to update neighbours http://en.cppreference.com/w/cpp/container/list

std::vector versus std::list begin O(1) end push_back size O(1) (since C++11) operator[] Not available erase(iterator) O(n) Iterator Type Random Access it++ is allowed it-- is allowed it + 5 is allowed Bidirectional it + 5 is not allowed

Iterator Categories Category Available Operations Random Access (e.g. vector) Bidirectional (e.g. list) Forward (e.g. forward_list) Read Increment Decrement *it it++ it-- it + 5 *it it++ it-- *it it++ http://en.cppreference.com/w/cpp/concept/Iterator

Replacing std::vector with std::list void remove_negatives(std::list<int>& integers) { for(std::list<int>::iterator it = integers.begin(); it != integers.end();) { if(*it < 0) { it = integers.erase(it); } else { it++; } void remove_negatives(std::vector<int>& integers) { for(std::vector<int>::iterator it = integers.begin(); it != integers.end();) { if(*it < 0) { it = integers.erase(it); } else { it++; } vector_vs_list.cpp

Replacing std::vector with std::list Because of iterators, we can quickly switch from vector to list This is one reason why iterators are so useful With std::list, remove_negatives is O(n) Be careful: not all code works interchangeably with all containers Change to explicit example vector_vs_list.cpp

Using C++11’s auto keyword Instead of specifying a type (such as int), we can use the auto keyword auto asks the compiler to determine the type for us Using auto can help… Save on typing Keep code compiling when you switch types around frequently Caution: You should always know what the actual type will be The type is still static auto does not mean the type can change dynamically – this is not python http://en.cppreference.com/w/cpp/language/auto

Simplifying Iterator Code with auto // Before C++11 for(std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { std::cout << *it << " "; } std::cout << "\n"; // With C++11 for(auto it = numbers.begin(); it != numbers.end(); ++it) { auto_iterators.cpp