Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Chapter 17 vector and Free Store Bjarne Stroustrup
Advertisements

Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup
Chapter 18 Vectors and Arrays
1.00 Lecture 37 A Brief Look at C++: A Guide to Reading C++ Programs.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Chapter 18 Vectors and Arrays John Keyser’s Modification of Slides by Bjarne Stroustrup
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Object Oriented Programming Elhanan Borenstein Lecture #12 copyrights © Elhanan Borenstein.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Chapter 10.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Review of C++ Programming Part II Sheng-Fang Huang.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
Lecture 11 vector and Free Store Bjarne Stroustrup
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 17 vector and Free Store Hartmut Kaiser
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
CSCE 121: Introduction to Program Design and Concepts, Honors Dr. J. Michael Moore Spring 2015 Set 16: Vector and Free Store CSCE : Set 16:
Defining New Types Lecture 21 Hartmut Kaiser
Generic Programming Using the C++ Standard Template Library.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
Pointers OVERVIEW.
Chapter 19 Vectors, templates, and exceptions John Keyser’s Modifications of Slides By Bjarne Stroustrup
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
C++ Memory Overview 4 major memory segments Key differences from Java
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 19 Vectors, templates, and exceptions Hartmut Kaiser
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Exceptions Bjarne Stroustrup
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 17: Vectors and Arrays 1 Based on slides created by Bjarne Stroustrup.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Standard-Library Exception Safety Bjarne Stroustrup Texas A&M University (and AT&T Labs – Research)
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 5 – September 4 th, 2001.
1 Introduction to Object Oriented Programming Chapter 10.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
CSCE Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 18: Vectors, Templates and Exceptions 1.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
C++ Functions A bit of review (things we’ve covered so far)
Chapter 18 Vectors and Arrays Bjarne Stroustrup
Motivation for Generic Programming in C++
CS212: Object Oriented Analysis and Design
“Generic Programming” ECE 297
Constructors and Destructors
Chapter 18 Vectors and Arrays
Motivation and Overview
Chapter 18 Vectors and Arrays
Collections Intro What is the STL? Templates, collections, & iterators
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Chapter 19 Vectors, templates, and exceptions
Chapter 17 vector and Free Store
Chapter 19 Vectors, templates, and exceptions
The Standard Template Library
Java Programming Language
Presentation transcript:

Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Abstract This is the third of the lectures exploring the design of the standard library vector and the techniques and language features used to implement it. Here, we deal with changing the size of a vector, parameterization of a vector with an element type (templates), and range checking (exceptions). This is the third of the lectures exploring the design of the standard library vector and the techniques and language features used to implement it. Here, we deal with changing the size of a vector, parameterization of a vector with an element type (templates), and range checking (exceptions). 2Stroustrup/Programming

Overview Vector revisited Vector revisited How are they implemented? How are they implemented? Pointers and free store Pointers and free store Destructors Destructors Initialization Initialization Copy and move Copy and move Arrays Arrays Array and pointer problems Array and pointer problems Changing size Changing size resize() and push_back() resize() and push_back() Templates Templates Range checking and exceptions Range checking and exceptions 3Stroustrup/Programming

Changing vector size Fundamental problem addressed Fundamental problem addressed We (humans) want abstractions that can change size (e.g., a vector where we can change the number of elements). However, in computer memory everything must have a fixed size, so how do we create the illusion of change? We (humans) want abstractions that can change size (e.g., a vector where we can change the number of elements). However, in computer memory everything must have a fixed size, so how do we create the illusion of change? Given vector v(n);// v.size()==n Given vector v(n);// v.size()==n we can change its size in three ways Resize it Resize it v.resize(10);// v now has 10 elements v.resize(10);// v now has 10 elements Add an element Add an element v.push_back(7);// add an element with the value 7 to the end of v // v.size() increases by 1 v.push_back(7);// add an element with the value 7 to the end of v // v.size() increases by 1 Assign to it Assign to it v = v2;// v is now a copy of v2 // v.size() now equals v2.size() v = v2;// v is now a copy of v2 // v.size() now equals v2.size() 4Stroustrup/Programming

Representing vector If you resize() or push_back() once, you’ll probably do it again; If you resize() or push_back() once, you’ll probably do it again; let’s prepare for that by sometimes keeping a bit of free space for future expansion let’s prepare for that by sometimes keeping a bit of free space for future expansion class vector { int sz; double* elem; int space;// number of elements plus “free space” // (the number of “slots” for new elements) public: // … }; 5 allocation:sz:  elements  (initialized)  -----free space  (uninitialized) 0 Stroustrup/Programming

Representing vector An empty vector (no free store use): An empty vector (no free store use): A vector(n) (no free space): A vector(n) (no free space): 6 N:0 Stroustrup/Programming

vector::reserve() First deal with space (allocation); given space all else is easy First deal with space (allocation); given space all else is easy Note: reserve() doesn’t mess with size or element values Note: reserve() doesn’t mess with size or element values void vector::reserve(int newalloc) // make the vector have space for newalloc elements { if (newalloc<=space) return;// never decrease allocation double* p = new double[newalloc];// allocate new space for (int i=0; i<sz; ++i) p[i]=elem[i];// copy old elements delete[ ] elem;// deallocate old space elem = p; space = newalloc; } 7Stroustrup/Programming

vector::resize() Given reserve(), resize() is easy Given reserve(), resize() is easy reserve() deals with space/allocation reserve() deals with space/allocation resize() deals with element values resize() deals with element values void vector::resize(int newsize) // make the vector have newsize elements // initialize each new element with the default value 0.0 { reserve(newsize);// make sure we have sufficient space for(int i = sz; i<newsize; ++i) elem[i] = 0;// initialize new elements sz = newsize; } 8Stroustrup/Programming

vector::push_back() Given reserve(), push_back() is easy Given reserve(), push_back() is easy reserve() deals with space/allocation reserve() deals with space/allocation push_back() just adds a value push_back() just adds a value void vector::push_back(double d) // increase vector size by one // initialize the new element with d { if (sz==0) // no space: grab some reserve(8); else if (sz==space) // no more free space: get more space reserve(2*space); elem[sz] = d;// add d at end ++sz;// and increase the size (sz is the number of elements) } 9Stroustrup/Programming

resize() and push_back() class vector {// an almost real vector of doubles int sz;// the size double* elem;// a pointer to the elements int space;// size+free_space public: // … constructors and destructors … double& operator[ ](int n) { return elem[n]; } // access: return reference int size() const { return sz; }// current size void resize(int newsize);// grow void push_back(double d);// add element void reserve(int newalloc);// get more space int capacity() const { return space; }// current available space }; 10Stroustrup/Programming

The this pointer A vector is an object A vector is an object vector v(10); vector v(10); vector* p = &v;// we can point to a vector object vector* p = &v;// we can point to a vector object Sometimes, vector’s member functions need to refer to that object Sometimes, vector’s member functions need to refer to that object The name of that “pointer to self” in a member function is this The name of that “pointer to self” in a member function is this v: this: 10 p: Stroustrup/Programming

The this pointer vector& vector::operator=(const vector& a) // like copy constructor, but we must deal with old elements { // … return *this;// by convention, // assignment returns a reference to its object: *this } void f(vector v1, vector v2, vector v3) { // … v1 = v2 = v3;// rare use made possible by operator=() returning *this // … } The this pointer has uses that are less obscure The this pointer has uses that are less obscure one of which we’ll get to in two minutes one of which we’ll get to in two minutes 12Stroustrup/Programming

Assignment Copy and swap is a powerful general idea Copy and swap is a powerful general idea vector& vector::operator=(const vector& a) // like copy constructor, but we must deal with old elements // make a copy of a then replace the current sz and elem with a’s { double* p = new double[a.sz];// allocate new space for (int i = 0; i<a.sz; ++i) p[i] = a.elem[i];// copy elements delete[ ] elem;// deallocate old space space = sz = a.sz;// set new size elem = p;// set new elements return *this; // return a self-reference } 13Stroustrup/Programming

Optimize assignment “Copy and swap” is the most general idea “Copy and swap” is the most general idea but not always the most efficient but not always the most efficient What if there already is sufficient space in the target vector? What if there already is sufficient space in the target vector? Then just copy! Then just copy! For example: a = b; For example: a = b; 14 sz: b: a: Stroustrup/Programming

Optimized assignment vector& vector::operator=(const vector& a) { if (this==&a) return *this;// self-assignment, no work needed if (a.sz<=space) {// enough space, no need for new allocation for (int i = 0; i<a.sz; ++i) elem[i] = a.elem[i];// copy elements sz = a.sz; return *this; } double* p = new double[a.sz];// copy and swap for (int i = 0; i<a.sz; ++i) p[i] = a.elem[i]; delete[ ] elem; space = sz = a.sz; elem = p; return *this; } 15Stroustrup/Programming

Templates But we don’t just want vector of double But we don’t just want vector of double We want vectors with element types we specify We want vectors with element types we specify vector vector vector // vector of pointers vector // vector of pointers vector >// vector of vectors vector >// vector of vectors vector vector We must make the element type a parameter to vector We must make the element type a parameter to vector vector must be able to take both built-in types and user- defined types as element types vector must be able to take both built-in types and user- defined types as element types This is not some magic reserved for the compiler; we can define our own parameterized types, called “templates” This is not some magic reserved for the compiler; we can define our own parameterized types, called “templates” 16Stroustrup/Programming

Templates The basis for generic programming in C++ The basis for generic programming in C++ Sometimes called “parametric polymorphism” Sometimes called “parametric polymorphism” Parameterization of types (and functions) by types (and integers) Parameterization of types (and functions) by types (and integers) Unsurpassed flexibility and performance Unsurpassed flexibility and performance Used where performance is essential (e.g., hard real time and numerics) Used where performance is essential (e.g., hard real time and numerics) Used where flexibility is essential (e.g., the C++ standard library) Used where flexibility is essential (e.g., the C++ standard library) Template definitions Template definitions template class Buffer { /* … */ }; template void fill(Buffer & b) { /* … */ } Template specializations (instantiations) Template specializations (instantiations) // for a class template, you specify the template arguments: Buffer buf;// for buf, T is char and N is 1024 // for a function template, the compiler deduces the template arguments: fill(buf);// for fill(), T is char and N is 1024; that’s what buf has 17Stroustrup/Programming

Parameterize with element type // an almost real vector of Ts: template class vector { // … }; vector vd;// T is double vector vi;// T is int vector > vvi;// T is vector vector > vvi;// T is vector // in which T is int vector vc;// T is char vector vpd;// T is double* vector *> vvpd;// T is vector * // in which T is double 18Stroustrup/Programming

Basically, vector is // an almost real vector of doubles: class vector { int sz;// the size double* elem;// a pointer to the elements int space;// size+free_space public: vector() : sz(0), elem(0), space(0) { }// default constructor explicit vector(int s) :sz(s), elem(new double[s]), space(s) { } // constructor vector(const vector&);// copy constructor vector& operator=(const vector&);// copy assignment ~vector() { delete[ ] elem; }// destructor double& operator[ ] (int n) { return elem[n]; }// access: return reference int size() const { return sz; }// the current size // … }; 19Stroustrup/Programming

Basically, vector is // an almost real vector of chars: class vector { int sz;// the size char* elem;// a pointer to the elements int space;// size+free_space public: vector() : sz{0}, elem{0}, space{0} { }// default constructor explicit vector(int s) :sz{s}, elem{new char[s]}, space{s} { } // constructor vector(const vector&);// copy constructor vector& operator=(const vector&);// copy assignment ~vector() { delete[ ] elem; }// destructor char& operator[ ] (int n) { return elem[n]; }// access: return reference int size() const { return sz; }// the current size // … }; 20Stroustrup/Programming

Basically, vector is // an almost real vector of Ts: // read “for all types T” (just like in math) template class vector { int sz;// the size T* elem;// a pointer to the elements int space;// size+free_space public: vector() : sz{0}, elem{0}, space{0};// default constructor explicit vector(int s) :sz{s}, elem{new T[s]}, space{s} { }// constructor vector(const vector&);// copy constructor vector& operator=(const vector&);// copy assignment vector(const vector&&);// move constructor vector& operator=(vector&&);// move assignment ~vector() { delete[ ] elem; }// destructor // … }; 21Stroustrup/Programming

Basically, vector is // an almost real vector of Ts: // read “for all types T” (just like in math) template class vector { int sz;// the size T* elem;// a pointer to the elements int space;// size+free_space public: // … constructors and destructors … T& operator[ ] (int n) { return elem[n]; } // access: return reference int size() const { return sz; }// the current size void resize(int newsize);// grow void push_back(double d);// add element void reserve(int newalloc);// get more space int capacity() const { return space; }// current available space // … }; 22Stroustrup/Programming

Templates Problems (“there is no free lunch”) Problems (“there is no free lunch”) Poor error diagnostics Poor error diagnostics Often spectacularly poor (but getting better in C++11; much better in C++14) Often spectacularly poor (but getting better in C++11; much better in C++14) Delayed error messages Delayed error messages Often at link time Often at link time All templates must be fully defined in each translation unit All templates must be fully defined in each translation unit (So place template definitions in header files (So place template definitions in header files Recommendation Recommendation Use template-based libraries Use template-based libraries Such as the C++ standard library Such as the C++ standard library E.g., vector, sort() E.g., vector, sort() Soon to be described in some detail Soon to be described in some detail Initially, write only very simple templates yourself Initially, write only very simple templates yourself Until you get more experience Until you get more experience 23Stroustrup/Programming

Range checking // an almost real vector of Ts: struct out_of_range { /* … */ }; template class vector { // … T& operator[ ](int n);// access // … }; template T& vector ::operator[ ](int n) { if (n<0 || sz<=n) throw out_of_range(); return elem[n]; } 24Stroustrup/Programming

Range checking void fill_vec(vector & v, int n)// initialize v with factorials { for (int i=0; i<n; ++i) v.push_back(factorial(i)); } int main() { vector v; try { fill_vec(v,10); for (int i=0; i<=v.size(); ++i) cout << "v[" << i << "]==" << v[i] << '\n'; } catch (out_of_range) {// we’ll get here (why?) cout << "out of range error"; return 1; }} 25Stroustrup/Programming

Exception handling We use exceptions to report errors We use exceptions to report errors We must ensure that use of exceptions We must ensure that use of exceptions Doesn’t introduce new sources of errors Doesn’t introduce new sources of errors Doesn’t complicate our code Doesn’t complicate our code Doesn’t lead to resource leaks Doesn’t lead to resource leaks Stroustrup/Programming 26

Resource management A resource is something that has to be acquired and must be released (explicitly and implicitly) Examples of resources Memory Locks File handles Thread handles Sockets Windows Stroustrup/Programming 27 void suspicious(int s, int x) { int* p = new int[s]; // acquire memory //... delete[] p; // release memory }

Resource management Why suspicious? It is easy to make mistakes with pointers and delete void suspicious(int s, int x) { int* p = new int[s]; // acquire memory //... if (x) p = q; // make p point to another object //... delete[] p; // release memory (but the wrong memory) } Stroustrup/Programming 28

Resource management Why suspicious? It’s easy not to get to the end of the function void suspicious(int s, int x) { int* p = new int[s]; // acquire memory //... if (x) return; // maybe we don’t get to the end: leak //... delete[] p; // release memory } Stroustrup/Programming 29

Resource management Why suspicious? It’s easy not to get to the end of the function void suspicious(int s, int x) { int* p = new int[s]; // acquire memory //... if (x) p[x] = v[x];// v[x] may throw an exception: leak //... delete[] p; // release memory } Stroustrup/Programming 30

Resource management Naïve, ugly, fix void suspicious(int s, int x) // messy code { int* p = new int[s]; // acquire memory vector v; //... try { if (x) p[x] = v[x];// may throw //... } catch (...) {// catch every exception delete[] p; // release memory throw; // re-throw the exception } //... delete[] p; // release memory } Stroustrup/Programming 31

Resource management Simple, general solution RAII: “Resource Acquisition is initialization” Also known as scoped resource management void f(vector & v, int s) { vector p(s); vector q(s); //... } // vector’s destructor releases memory upon scope exit Stroustrup/Programming 32

Resource management But what about functions creating objects? Traditional, error-prone solution: return a pointer vector * make_vec() // make a filled vector { vector * p = new vector ; // we allocate on free store //... fill the vector with data; this may throw an exception... return p; } // now users have to remember to delete // they will occasionally forget: leak! Stroustrup/Programming 33

Resource management But what about functions creating objects? Improved solution: use std::unique_ptr unique_ptr > make_vec() // make a filled vector { unique_ptr > p {new vector }; // allocate on free store // … fill the vector with data; this may throw an exception … return p.release(); } // users don’t have to delete; no delete in user code // a unique_ptr owns its object and deletes it automatically Stroustrup/Programming 34

Resource management But what about functions creating objects? Even better solution: use std::make_unique C++14 only (unless you have an implementation of make_unique) unique_ptr > make_vec() // make a filled vector { auto p = make_unique{vector }; // allocate on free store // … fill the vector with data; this may throw an exception … return p; } // no new in user code Stroustrup/Programming 35

Resource management But what about functions creating objects? Best solution: don’t mess with pointers (of any sort) at all Return the object itself vector make_vec() // make a filled vector { vector res; //... fill the vector with data; this may throw an exception... return res; // vector’s move constructor efficiently transfers ownership } // don’t use pointers unless you really need them Stroustrup/Programming 36

RAII (Resource Acquisition Is Initialization) Vector Vector acquires memory for elements in its constructor acquires memory for elements in its constructor Manage it (changing size, controlling access, etc.) Manage it (changing size, controlling access, etc.) Gives back (releases) the memory in the destructor Gives back (releases) the memory in the destructor This is a special case of the general resource management strategy called RAII This is a special case of the general resource management strategy called RAII Also called “scoped resource management” Also called “scoped resource management” Use it wherever you can Use it wherever you can It is simpler and cheaper than anything else It is simpler and cheaper than anything else It interacts beautifully with error handling using exceptions It interacts beautifully with error handling using exceptions Examples of resources: Examples of resources: Memory, file handles, sockets, I/O connections (iostreams handle those using RAII), locks, widgets, threads. Memory, file handles, sockets, I/O connections (iostreams handle those using RAII), locks, widgets, threads. 37Stroustrup/Programming

A confession The standard library vector doesn’t guarantee range checking of [ ] The standard library vector doesn’t guarantee range checking of [ ] You have been using You have been using Either our debug version, called Vector, which does check Either our debug version, called Vector, which does check Or a standard library version that does check (several do) Or a standard library version that does check (several do) Unless your version of the standard library checks, we “cheated” Unless your version of the standard library checks, we “cheated” In std_lib_facilities.h, we use the nasty trick (a macro substitution) of redefining vector to mean Vector In std_lib_facilities.h, we use the nasty trick (a macro substitution) of redefining vector to mean Vector #define vector Vector (This trick is nasty because what you see looking at the code is not what compiler sees – in real code macros are a significant source of obscure errors) (This trick is nasty because what you see looking at the code is not what compiler sees – in real code macros are a significant source of obscure errors) We did the same for string We did the same for string 38Stroustrup/Programming

What the standard guarantees // the standard library vector doesn’t guarantee a range check in operator[ ]: template class vector { // … T& at(int n);// checked access T& operator[ ](int n);// unchecked access }; template T& vector ::at (int n) { if (n<0 || sz<=n) throw out_of_range(); return elem[n]; } template T& vector ::operator[ ](int n) { return elem[n]; } 39Stroustrup/Programming

What the standard guarantees Why doesn’t the standard guarantee checking? Why doesn’t the standard guarantee checking? Checking cost in speed and code size Checking cost in speed and code size Not much; don’t worry Not much; don’t worry No student project needs to worry No student project needs to worry Few real-world projects need to worry Few real-world projects need to worry Some projects need optimal performance Some projects need optimal performance Think huge (e.g., Google) and tiny (e.g., cell phone) Think huge (e.g., Google) and tiny (e.g., cell phone) The standard must serve everybody The standard must serve everybody You can build checked on top of optimal You can build checked on top of optimal You can’t build optimal on top of checked You can’t build optimal on top of checked Some projects are not allowed to use exceptions Some projects are not allowed to use exceptions Old projects with pre-exception parts Old projects with pre-exception parts High reliability, hard-real-time code (think airplanes) High reliability, hard-real-time code (think airplanes) 40Stroustrup/Programming

Access to const vectors template class vector { // … T& at(int n);// checked access const T& at(int n) const;// checked access T& operator[ ](int n);// unchecked access const T& operator[ ](int n) const;// unchecked access // … }; void f(const vector cvd, vector vd) { // … double d1 = cvd[7];// call the const version of [ ] double d2 = vd[7];// call the non-const version of [ ] cvd[7] = 9;// error: call the const version of [ ] vd[7] = 9;// call the non-const version of [ ]: ok } 41Stroustrup/Programming

String A string is rather similar to a vector A string is rather similar to a vector E.g. size(), [ ], push_back() E.g. size(), [ ], push_back() Built with the same language features and techniques Built with the same language features and techniques A string is optimized for character string manipulation A string is optimized for character string manipulation Concatenation (+) Concatenation (+) Can produce a C-style string (c_str()) Can produce a C-style string (c_str()) >> input terminated by whitespace >> input terminated by whitespace Small strings don’t use free store (characters are stored in the handle) Small strings don’t use free store (characters are stored in the handle) 42 6 Howyd! Stroustrup/Programming \0

Next lecture An introduction to the STL, the containers and algorithms part of the C++ standard library. Here we’ll meet sequences, iterators, and containers (such as vector, list, and map). The algorithms include find(), find_if(), sort(), copy(), copy_if(), and accumulate(). An introduction to the STL, the containers and algorithms part of the C++ standard library. Here we’ll meet sequences, iterators, and containers (such as vector, list, and map). The algorithms include find(), find_if(), sort(), copy(), copy_if(), and accumulate(). 43Stroustrup/Programming