C++ STL, Smart Pointers Intro CSE 333 Spring 2018

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

C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
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.
Review of C++ Programming Part II Sheng-Fang Huang.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
Data Structures Using C++ 2E
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
1 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
C++ Review STL CONTAINERS.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Motivation for Generic Programming in C++
“Generic Programming” ECE 297
Pointers and Dynamic Arrays
C++ Programming:. Program Design Including
Motivation and Overview
Programming Abstractions
Standard Template Library (STL)
Pointers, Pointers, Pointers CSE 333 Spring 2018
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
C++ References, Const, Classes CSE 333 Spring 2018
What remains Topics Assignments Final exam
C++ Inheritance II, Casting CSE 333 Spring 2018
10 – Iterators C++ Templates 4.6 The Iterator pgs
C++ Standard Template Library CSE 333 Spring 2018
Dynamic Memory Allocation
C++ Intro CSE 333 Spring 2018 Instructor: Justin Hsia
C++ Constructor Insanity CSE 333 Spring 2018
Client-side Networking CSE 333 Spring 2018
C++ Templates CSE 333 Spring 2018
C++ Encapsulation, Heap CSE 333 Spring 2018
C++ Inheritance I CSE 333 Spring 2018
C++ Smart Pointers CSE 333 Spring 2018
The Standard Template Library
References Revisited CSE 333 Spring 2018
References Revisited CSE 333 Summer 2018
Introduction to C++ Linear Linked Lists
Iterators and STL Containers
C++ Smart Pointers CSE 333 Autumn 2018
C++ Templates CSE 333 Summer 2018
C++ Constructor Insanity CSE 333 Summer 2018
C++ Standard Template Library CSE 333 Autumn 2018
C++ Standard Template Library CSE 333 Summer 2018
Concurrency and Processes CSE 333 Spring 2018
C++ Standard Template Library CSE 333 Winter 2019
C++ Templates CSE 333 Autumn 2018
C++ Constructor Insanity CSE 333 Autumn 2018
Lab4 problems More about templates Some STL
Pointers and dynamic objects
Standard Template Library
C++ Constructor Insanity CSE 333 Winter 2019
C++ Smart Pointers CSE 333 Winter 2019
Dynamic allocation (continued)
References Revisited CSE 333 Autumn 2018
References Revisited CSE 333 Winter 2019
C++ Templates CSE 333 Winter 2019
CS 144 Advanced C++ Programming March 21 Class Meeting
An Introduction to STL.
C++ Constructor Insanity CSE 333 Spring 2019
Chapter 3 Lists, Stacks, and Queues
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
CS 144 Advanced C++ Programming April 30 Class Meeting
C++ Standard Template Library CSE 333 Spring 2019
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

C++ STL, Smart Pointers Intro CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon Huang Wei Lin

Administrivia Exercise 12 released today, due Monday Midterm is next Friday (5/4) @ 5–6 pm in GUG 220 1 double-sided page of handwritten notes; (subject to change) reference sheet provided on exam Topics: everything from lecture, exercises, project, etc. up through hw2 and C++ templates Old exams on course website, review in section next week

Lecture Outline STL (finish) List Map Smart Pointers Intro

STL list A generic doubly-linked list http://www.cplusplus.com/reference/stl/list/ Elements are not stored in contiguous memory locations Does not support random access (e.g. cannot do list[5]) Some operations are much more efficient than vectors Constant time insertion, deletion anywhere in list Can iterate forward or backwards Has a built-in sort member function Doesn’t copy! Manipulates list structure instead of element values

list Example listexample.cc #include <list> 4/25/2018 list Example listexample.cc #include <list> #include <algorithm> #include "Tracer.h" using namespace std; void PrintOut(const Tracer& p) { cout << " printout: " << p << endl; } int main(int argc, char** argv) { Tracer a, b, c; list<Tracer> lst; lst.push_back(c); lst.push_back(a); lst.push_back(b); cout << "sort:" << endl; lst.sort(); cout << "done sort!" << endl; for_each(lst.begin(), lst.end(), &PrintOut); return 0;

STL map One of C++’s associative containers: a key/value table, implemented as a tree http://www.cplusplus.com/reference/stl/map/ General form: Keys must be unique multimap allows duplicate keys Efficient lookup (O(log n)) and insertion (O(log n)) Access value via name[key] Elements are of type pair<key_type, value_type> and are stored in sorted order Key type must support less-than operator (<) If iterating over map elements, key is field first, value is field second map<key_type, value_type> name;

map Example mapexample.cc 4/25/2018 map Example mapexample.cc void PrintOut(const pair<Tracer,Tracer>& p) { cout << "printout: [" << p.first << "," << p.second << "]" << endl; } int main(int argc, char** argv) { Tracer a, b, c, d, e, f; map<Tracer,Tracer> table; map<Tracer,Tracer>::iterator it; table.insert(pair<Tracer,Tracer>(a, b)); table[c] = d; table[e] = f; cout << "table[e]:" << table[e] << endl; it = table.find(c); cout << "PrintOut(*it), where it = table.find(c)" << endl; PrintOut(*it); cout << "iterating:" << endl; for_each(table.begin(), table.end(), &PrintOut); return 0; Run vectoralgos to see Tracer output – lots of copying!!!

Basic map Usage animals.cc

Homegrown pair<>

Unordered Containers (C++11) unordered_map, unordered_set And related classes unordered_multimap, unordered_multiset Average case for key access is O(1) But range iterators can be less efficient than ordered map/set See C++ Primer, online references for details

Lecture Outline STL (finish) List Map Smart Pointers Intro

Motivation We noticed that STL was doing an enormous amount of copying One solution: store pointers in containers instead of objects But who’s responsible for deleting and when???

C++ Smart Pointers A smart pointer is an object that stores a pointer to a heap-allocated object A smart pointer looks and behaves like a regular C++ pointer By overloading *, ->, [], etc. These can help you manage memory The smart pointer will delete the pointed-to object at the right time (timing depends on what kind of smart pointer), including invoking the object’s destructor With correct use of smart pointers, you no longer have to remember when to delete new’d memory!

A Toy Smart Pointer We can implement a simple one with: A constructor that accepts a pointer A destructor that frees the pointer Overloaded * and -> operators that access the pointer

ToyPtr Class Template ToyPtr.cc #ifndef _TOYPTR_H_ #define _TOYPTR_H_ 4/25/2018 ToyPtr Class Template ToyPtr.cc #ifndef _TOYPTR_H_ #define _TOYPTR_H_ template <typename T> class ToyPtr { public: ToyPtr(T *ptr) : ptr_(ptr) { } // constructor ~ToyPtr() { // destructor if (ptr_ != nullptr) { delete ptr_; ptr_ = nullptr; } T &operator*() { return *ptr_; } // * operator T *operator->() { return ptr_; } // -> operator private: T *ptr_; // the pointer itself }; #endif // _TOYPTR_H_ The -> operator automatically dereferences its return value before calling its argument using the built-in pointer dereference, not operator*, so you could have the following class:

ToyPtr Example usetoy.cc #include <iostream> #include "ToyPtr.h" 4/25/2018 ToyPtr Example usetoy.cc #include <iostream> #include "ToyPtr.h" // simply struct to use typedef struct { int x = 1, y = 2; } Point; std::ostream &operator<<(std::ostream &out, const Point &rhs) { return out << "(" << rhs.x << "," << rhs.y << ")"; } int main(int argc, char **argv) { // Create a dumb pointer Point *leak = new Point; // Create a "smart" pointer (OK, it's still pretty dumb) ToyPtr<Point> notleak(new Point); std::cout << " *leak: " << *leak << std::endl; std::cout << " leak->x: " << leak->x << std::endl; std::cout << " *notleak: " << *notleak << std::endl; std::cout << "notleak->x: " << notleak->x << std::endl; return 0; bash$ ./usepoint bash$ valgrind --leak-check=full ./usepoint

What Makes This a Toy? Can’t handle: Arrays Copying Reassignment Comparison … plus many other subtleties… Luckily, others have built non-toy smart pointers! More next lecture!

Extra Exercise #1 Take one of the books from HW2’s test_tree and: Read in the book, split it into words (you can use your hw2) For each word, insert the word into an STL map The key is the word, the value is an integer The value should keep track of how many times you’ve seen the word, so each time you encounter the word, increment its map element Thus, build a histogram of word count Print out the histogram in order, sorted by word count Bonus: Plot the histogram on a log-log scale (use Excel, gnuplot, etc.) x-axis: log(word number), y-axis: log(word count)

Extra Exercise #2 Implement Triple, a class template that contains three “things,” i.e. it should behave like std::pair but hold 3 objects instead of 2 The “things” can be of different types Write a program that: Instantiates several Triples that contain ToyPtr<int>s Insert the Triples into a vector Reverse the vector Doesn’t have any memory errors (use Valgrind!) Note: You will need to update ToyPtr.h – how?