20 containers

42
Chapter 20 Chapter 20 The STL The STL (containers, iterators, and (containers, iterators, and algorithms) algorithms) Bjarne Stroustrup Bjarne Stroustrup www.stroustrup.com/Programming www.stroustrup.com/Programming

Upload: kuku288

Post on 13-May-2017

224 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 20 Containers

Chapter 20 Chapter 20 The STLThe STL

(containers, iterators, and algorithms)(containers, iterators, and algorithms)

Bjarne StroustrupBjarne Stroustrup

www.stroustrup.com/Programmingwww.stroustrup.com/Programming

Page 2: 20 Containers

OverviewOverview Common tasks and idealsCommon tasks and ideals Generic programmingGeneric programming Containers, algorithms, and iteratorsContainers, algorithms, and iterators The simplest algorithm: find()The simplest algorithm: find() Parameterization of algorithmsParameterization of algorithms

find_if() and function objectsfind_if() and function objects Sequence containersSequence containers

vector and listvector and list Associative containersAssociative containers

map, setmap, set Standard algorithmsStandard algorithms

copy, sort, …copy, sort, … Input iterators and output iteratorsInput iterators and output iterators

List of useful facilitiesList of useful facilities Headers, algorithms, containers, function objectsHeaders, algorithms, containers, function objects

33Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 3: 20 Containers

Common tasksCommon tasks Collect data into containersCollect data into containers Organize dataOrganize data

For printingFor printing For fast accessFor fast access

Retrieve data itemsRetrieve data items By index By index (e.g., get the (e.g., get the NNth element)th element) By value By value (e.g., get the first element with the value (e.g., get the first element with the value "Chocolate""Chocolate")) By properties By properties (e.g., get the first elements where (e.g., get the first elements where ““age<64age<64””))

Add dataAdd data Remove dataRemove data Sorting and searchingSorting and searching Simple numeric operationsSimple numeric operations

44Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 4: 20 Containers

ObservationObservation

We can (already) write programs that are very similar We can (already) write programs that are very similar independent of the data type usedindependent of the data type used Using an Using an intint isn isn’’t that different from using a t that different from using a doubledouble Using a Using a vector<int>vector<int> isn isn’’t that different from using a t that different from using a

vector<string>vector<string>

55Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 5: 20 Containers

IdealsIdeals

WeWe’’d like to write common programming tasks so that d like to write common programming tasks so that we donwe don’’t have to re-do the work each time we find a t have to re-do the work each time we find a new way of storing the data or a slightly different way new way of storing the data or a slightly different way of interpreting the dataof interpreting the data Finding a value in a Finding a value in a vectorvector isn isn’’t all that different from t all that different from

finding a value in a finding a value in a listlist or an array or an array Looking for a Looking for a stringstring ignoring case isn ignoring case isn’’t all that different t all that different

from looking at a from looking at a stringstring not ignoring case not ignoring case Graphing experimental data with exact values isnGraphing experimental data with exact values isn’’t all that t all that

different from graphing data with rounded valuesdifferent from graphing data with rounded values Copying a file isnCopying a file isn’’t all that different from copying a vectort all that different from copying a vector

66Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 6: 20 Containers

Ideals Ideals (continued)(continued)

Code thatCode that’’ss Easy to readEasy to read Easy to modifyEasy to modify RegularRegular Short Short Fast Fast

Uniform access to dataUniform access to data Independently of how it is storedIndependently of how it is stored Independently of its typeIndependently of its type

……

77Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 7: 20 Containers

Ideals Ideals (continued)(continued)

…… Type-safe access to dataType-safe access to data Easy traversal of dataEasy traversal of data Compact storage of dataCompact storage of data FastFast

Retrieval of dataRetrieval of data Addition of dataAddition of data Deletion of dataDeletion of data

Standard versions of the most common algorithmsStandard versions of the most common algorithms Copy, find, search, sort, sum, …Copy, find, search, sort, sum, …

88Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 8: 20 Containers

Examples Examples Sort a vector of stringsSort a vector of strings Find an number in a phone book, given a nameFind an number in a phone book, given a name Find the highest temperatureFind the highest temperature Find all values larger than 800Find all values larger than 800 Find the first occurrence of the value 17Find the first occurrence of the value 17 Sort the telemetry records by unit numberSort the telemetry records by unit number Sort the telemetry records by time stampSort the telemetry records by time stamp Find the first value larger than Find the first value larger than ““PetersenPetersen””?? What is the largest amount seen?What is the largest amount seen? Find the first difference between two sequencesFind the first difference between two sequences Compute the pairwise product of the elements of two sequencesCompute the pairwise product of the elements of two sequences What are the highest temperatures for each day in a month?What are the highest temperatures for each day in a month? What are the top 10 best-sellers?What are the top 10 best-sellers? WhatWhat’’s the entry for s the entry for ““C++C++”” (say, in Google)? (say, in Google)? WhatWhat’’s the sum of the elements?s the sum of the elements?

99Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 9: 20 Containers

1010

Generic programmingGeneric programming Generalize algorithmsGeneralize algorithms

Sometimes called Sometimes called ““lifting an algorithmlifting an algorithm”” The aim (for the end user) isThe aim (for the end user) is

Increased correctnessIncreased correctness Through better specificationThrough better specification

Greater range of usesGreater range of uses Possibilities for re-usePossibilities for re-use

Better performanceBetter performance Through wider use of tuned librariesThrough wider use of tuned libraries Unnecessarily slow code will eventually be thrown awayUnnecessarily slow code will eventually be thrown away

GGo from the concrete to the more abstracto from the concrete to the more abstract The other way most often leads to bloatThe other way most often leads to bloat

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 10: 20 Containers

1111

Lifting example Lifting example (concrete algorithms)(concrete algorithms)

double sum(double array[], int n)double sum(double array[], int n) // // one concrete algorithm (doubles in array)one concrete algorithm (doubles in array){{

double s = 0;double s = 0;for (int i = 0; i < n; ++i ) s = s + array[i];for (int i = 0; i < n; ++i ) s = s + array[i];return s;return s;

}}

struct Node { Node* next; int data; };struct Node { Node* next; int data; };

int sum(Node* first)int sum(Node* first) // // another concrete algorithm (ints in list)another concrete algorithm (ints in list){{

int s = 0;int s = 0;while (first) {while (first) { // // terminates when expression is false or zeroterminates when expression is false or zeros += first->data;s += first->data;first = first->next;first = first->next;}}return s;return s;

}}Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 11: 20 Containers

1212

Lifting example Lifting example (abstract the data structure)(abstract the data structure)

// // pseudo-code for a more general version of both algorithmspseudo-code for a more general version of both algorithms

int sum(data)int sum(data) // // somehow parameterize with the data structuresomehow parameterize with the data structure{{

int s = 0;int s = 0; // // initializeinitializewhile (not at end) {while (not at end) { // // loop through all elementsloop through all elements s = s + get value;s = s + get value; // // compute sumcompute sum get next data element;get next data element;}}return s;return s;// // return resultreturn result

}}

We need three operations (on the data structure):We need three operations (on the data structure): not at endnot at end get valueget value get next data elementget next data element

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 12: 20 Containers

1313

Lifting example Lifting example (STL version)(STL version)

// // Concrete STL-style code for a more general version of both algorithmsConcrete STL-style code for a more general version of both algorithms

template<class Iter, class T> template<class Iter, class T> // // Iter should be an Input_iteratorIter should be an Input_iterator// // T should be something we can + and =T should be something we can + and =

T sum(Iter first, Iter last, T s)T sum(Iter first, Iter last, T s) // // T is the T is the ““accumulator typeaccumulator type””{{

while (first!=last) {while (first!=last) {s = s + *first;s = s + *first;++first;++first;}}return s;return s;

}} Let the user initialize the accumulatorLet the user initialize the accumulator

float a[] = { 1,2,3,4,5,6,7,8 }; float a[] = { 1,2,3,4,5,6,7,8 }; double d = 0;double d = 0;d = sum(a,a+sizeof(a)/sizeof(*a),d);d = sum(a,a+sizeof(a)/sizeof(*a),d);

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 13: 20 Containers

1414

Lifting exampleLifting example Almost the standard library accumulateAlmost the standard library accumulate

I I simplifiedsimplified a bit for terseness a bit for terseness(see 21.5 for more generality and more details)(see 21.5 for more generality and more details)

Works forWorks for arraysarrays vectorvectorss listlistss istreamistreamss ……

Runs as fast as Runs as fast as ““hand-craftedhand-crafted”” code code Given decent inliningGiven decent inlining

The codeThe code’’s requirements on its data has become explicits requirements on its data has become explicit We understand the code betterWe understand the code better

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 14: 20 Containers

The STLThe STL

Part of the ISO C++ Standard LibraryPart of the ISO C++ Standard Library Mostly non-numericalMostly non-numerical

Only 4 standard algorithms specifically do computationOnly 4 standard algorithms specifically do computation Accumulate, inner_product, partial_sum, adjacent_differenceAccumulate, inner_product, partial_sum, adjacent_difference

Handles textual data as well as numeric dataHandles textual data as well as numeric data E.g. stringE.g. string

Deals with organization of code and dataDeals with organization of code and data Built-in types, user-defined types, and data structuresBuilt-in types, user-defined types, and data structures

Optimizing disk access was among its original usesOptimizing disk access was among its original uses Performance was always a key concernPerformance was always a key concern

1515Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 15: 20 Containers

The STLThe STL Designed by Alex StepanovDesigned by Alex Stepanov General aim: The most general, mostGeneral aim: The most general, most

efficient, most flexible representationefficient, most flexible representationof concepts (ideas, algorithms)of concepts (ideas, algorithms) Represent separate concepts separately in codeRepresent separate concepts separately in code Combine concepts freely wherever meaningfulCombine concepts freely wherever meaningful

General aim to make programming General aim to make programming ““like mathlike math”” or even or even ““Good programming Good programming isis math math”” works for integers, for floating-point numbers, for works for integers, for floating-point numbers, for

polynomials, for …polynomials, for …

1616Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 16: 20 Containers

Basic modelBasic model AlgorithmsAlgorithms

sort, find, search, copy, …sort, find, search, copy, …

ContainersContainers vector, list, map, unordered_map, …vector, list, map, unordered_map, …

1717

iterators

• Separation of concernsSeparation of concerns– Algorithms manipulate Algorithms manipulate

data, but dondata, but don’’t know t know about containersabout containers

– Containers store data, but Containers store data, but dondon’’t know about t know about algorithmsalgorithms

– Algorithms and Algorithms and containers interact containers interact through iteratorsthrough iterators

• Each container has its Each container has its own iterator typesown iterator types

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 17: 20 Containers

The STLThe STL An ISO C++ standard framework of about 10 An ISO C++ standard framework of about 10

containers and about 60 algorithms connected by containers and about 60 algorithms connected by iteratorsiterators Other organizations provide more containers and Other organizations provide more containers and

algorithms in the style of the STLalgorithms in the style of the STL Boost.org, Microsoft, SGI, …Boost.org, Microsoft, SGI, …

Probably the currently best known and most widely Probably the currently best known and most widely used example of generic programmingused example of generic programming

1818Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 18: 20 Containers

The STLThe STL If you know the basic concepts and a few examples you If you know the basic concepts and a few examples you

can use the restcan use the rest DocumentationDocumentation

SGISGI http://www.sgi.com/tech/stl/ (recommended because of clarity)http://www.sgi.com/tech/stl/ (recommended because of clarity)

DinkumwareDinkumware http://www.dinkumware.com/refxcpp.html (beware of several library http://www.dinkumware.com/refxcpp.html (beware of several library

versions)versions) Rogue WaveRogue Wave

http://www.roguewave.com/support/docs/sourcepro/stdlibug/index.htmlhttp://www.roguewave.com/support/docs/sourcepro/stdlibug/index.html More accessible and less complete documentationMore accessible and less complete documentation

Appendix BAppendix B

1919Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 19: 20 Containers

Basic modelBasic model A pair of iterators defines a sequenceA pair of iterators defines a sequence

The beginning (points to the first element – if any)The beginning (points to the first element – if any) The end (points to the one-beyond-the-last element)The end (points to the one-beyond-the-last element)

2020

begin: end:

• An iterator is a type that supports the An iterator is a type that supports the ““iterator operationsiterator operations””• ++ Go to next element++ Go to next element• * Get value* Get value• == Does this iterator point to the same element as that iterator?== Does this iterator point to the same element as that iterator?

• Some iterators support more operations (e.g. --, +, and [ ])Some iterators support more operations (e.g. --, +, and [ ])Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 20: 20 Containers

ContainersContainers(hold sequences in difference ways)(hold sequences in difference ways)

vectorvector

listlist(doubly linked)(doubly linked)

setset(a kind of tree)(a kind of tree)

2121

0 1 2 3

0 1

10

6

2

5

7

3 4

2

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 21: 20 Containers

The simplest algorithm: The simplest algorithm: find()find()

// // Find the first element that equals a valueFind the first element that equals a value

template<class In, class T>template<class In, class T>In find(In first, In last, const T& val)In find(In first, In last, const T& val){{

while (first!=last && *first != val) ++first;while (first!=last && *first != val) ++first;return first;return first;

}}

void f(vector<int>& v, int x)void f(vector<int>& v, int x) // // find an int in a vectorfind an int in a vector{{

vector<int>::iterator p = find(v.begin(),v.end(),x);vector<int>::iterator p = find(v.begin(),v.end(),x);if (p!=v.end()) { /* if (p!=v.end()) { /* we found we found x x */ }*/ }// // ……

}}

2222

begin: end:

We can ignore (We can ignore (““abstract awayabstract away””) the differences between containers) the differences between containersStroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 22: 20 Containers

find()find()generic for both element type and container typegeneric for both element type and container type

void f(vector<int>& v, int x)void f(vector<int>& v, int x) // // works for works for vectorvector of of intintss{{

vector<int>::vector<int>::iterator p = find(v.begin(),v.end(),x);iterator p = find(v.begin(),v.end(),x);if (p!=v.end()) { /* if (p!=v.end()) { /* we foundwe found xx */ }*/ }// // ……

}}

void f(list<string>& v, string x)void f(list<string>& v, string x) // // works for works for listlist of of stringstringss{{

list<string>::list<string>::iterator p = find(v.begin(),v.end(),x);iterator p = find(v.begin(),v.end(),x);if (p!=v.end()) { /* if (p!=v.end()) { /* we foundwe found x x */ }*/ }// // ……

}}

void f(set<double>& v, double x)void f(set<double>& v, double x) // // works for works for setset of of doubledoubless{{

set<double>::set<double>::iterator p = find(v.begin(),v.end(),x);iterator p = find(v.begin(),v.end(),x);if (p!=v.end()) { /* if (p!=v.end()) { /* we found we found x x */ }*/ }// // ……

}}2323Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 23: 20 Containers

Algorithms and iteratorsAlgorithms and iterators An iterator points to (refers to, denotes) an element of a sequenceAn iterator points to (refers to, denotes) an element of a sequence The end of the sequence is The end of the sequence is ““one past the last elementone past the last element””

notnot ““the last elementthe last element”” ThatThat’’s necessary to elegantly represent an empty sequences necessary to elegantly represent an empty sequence One-past-the-last-element isnOne-past-the-last-element isn’’t an elementt an element

You can compare an iterator pointing to itYou can compare an iterator pointing to it You canYou can’’t dereference it (read its value)t dereference it (read its value)

Returning the end of the sequence is the standard idiom for Returning the end of the sequence is the standard idiom for ““not not foundfound”” or or ““unsuccessfulunsuccessful””

2424

0 1 2 3

the end:

An empty sequence:

begin: end:some iterator:

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 24: 20 Containers

Simple algorithm: Simple algorithm: find_if()find_if() Find the first element that matches a criterion (predicate)Find the first element that matches a criterion (predicate)

Here, a predicate takes one argument and returns a Here, a predicate takes one argument and returns a boolbool

template<class In, class Pred>template<class In, class Pred>In find_if(In first, In last, Pred pred)In find_if(In first, In last, Pred pred){{

while (first!=last && !pred(*first)) ++first;while (first!=last && !pred(*first)) ++first;return first;return first;

}}

void f(vector<int>& v)void f(vector<int>& v){{

vector<int>::iterator p = find_if(v.begin(),v.end,Odd());vector<int>::iterator p = find_if(v.begin(),v.end,Odd());if (p!=v.end()) { /* if (p!=v.end()) { /* we found an odd number we found an odd number */ }*/ }// // ……

}}

2525

A predicate

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 25: 20 Containers

PredicatesPredicates A predicate (of one argument) is a function or a function object A predicate (of one argument) is a function or a function object

that takes an argument and returns a that takes an argument and returns a boolbool For exampleFor example

A functionA functionbool odd(int i) { return i%2; } // bool odd(int i) { return i%2; } // % % is the remainder (modulo) operatoris the remainder (modulo) operatorodd(7);odd(7); // // callcall odd odd: is 7 odd: is 7 odd??

A function objectA function objectstruct Odd {struct Odd {

bool operator()(int i) const { return i%2; }bool operator()(int i) const { return i%2; }};};Odd odd;Odd odd; // // make an objectmake an object odd odd of typeof type Odd Oddodd(7);odd(7); // // call call oddodd: is 7 odd?: is 7 odd?

2626Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 26: 20 Containers

Function objectsFunction objects

A concrete example using stateA concrete example using state

template<class T> struct Less_than {template<class T> struct Less_than {T val;T val; // // value to compare withvalue to compare withLess_than(T& x) :val(x) { }Less_than(T& x) :val(x) { }bool operator()(const T& x) const { return x < val; }bool operator()(const T& x) const { return x < val; }

};};

// // find x<43 in vector<int> :find x<43 in vector<int> :p=find_if(v.begin(), v.end(), Less_than(43)); p=find_if(v.begin(), v.end(), Less_than(43));

// // find x<find x<"perfection" "perfection" in list<string>:in list<string>:q=find_if(ls.begin(), ls.end(), Less_than("perfection")); q=find_if(ls.begin(), ls.end(), Less_than("perfection"));

2727Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 27: 20 Containers

Function objectsFunction objects A very efficient techniqueA very efficient technique

inlining very easyinlining very easy and effective with current compilersand effective with current compilers

Faster than equivalent functionFaster than equivalent function And sometimes you canAnd sometimes you can’’t write an equivalent functiont write an equivalent function

The main method of policy parameterization in the STLThe main method of policy parameterization in the STL Key to emulating functional programming techniques in C++Key to emulating functional programming techniques in C++

2828Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 28: 20 Containers

Policy parameterizationPolicy parameterization Whenever you have a useful algorithm, you eventually want to Whenever you have a useful algorithm, you eventually want to

parameterize it by a parameterize it by a ““policypolicy””.. For example, we need to parameterize sort by the comparison criteriaFor example, we need to parameterize sort by the comparison criteria

struct Record {struct Record {string name;string name; // // standard string for ease of usestandard string for ease of usechar addr[24];char addr[24]; // // old C-style string to match database layoutold C-style string to match database layout// // ……

};};

vector<Record> vr;vector<Record> vr;// // ……sort(vr.begin(), vr.end(), Cmp_by_name());sort(vr.begin(), vr.end(), Cmp_by_name()); // // sort bysort by name namesort(vr.begin(), vr.end(), Cmp_by_addr());sort(vr.begin(), vr.end(), Cmp_by_addr()); // // sort bysort by addr addr

2929Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 29: 20 Containers

ComparisonsComparisons// // Different comparisons forDifferent comparisons for Rec Rec objectsobjects::

struct Cmp_by_name {struct Cmp_by_name {bool operator()(const Rec& a, const Rec& b) constbool operator()(const Rec& a, const Rec& b) const

{ return a.name < b.name; } { return a.name < b.name; } // // look at the name field of Reclook at the name field of Rec};};

struct Cmp_by_addr {struct Cmp_by_addr {bool operator()(const Rec& a, const Rec& b) constbool operator()(const Rec& a, const Rec& b) const

{ return 0 < strncmp(a.addr, b.addr, 24); }{ return 0 < strncmp(a.addr, b.addr, 24); } // // correct?correct?};};

// // note how the comparison function objects are used to hide uglynote how the comparison function objects are used to hide ugly// // and error-prone codeand error-prone code

3030Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 30: 20 Containers

Policy parameterizationPolicy parameterization Whenever you have a useful algorithm, you eventually want to Whenever you have a useful algorithm, you eventually want to

parameterize it by a parameterize it by a ““policypolicy””.. For example, we need to parameterize sort by the comparison criteriaFor example, we need to parameterize sort by the comparison criteria

vector<Record> vr;vector<Record> vr;// // ……sort(vr.begin(), vr.end(),sort(vr.begin(), vr.end(),

[] (const Rec& a, const Rec& b)[] (const Rec& a, const Rec& b){ return a.name < b.name; } { return a.name < b.name; } // // sort bysort by name name););

sort(vr.begin(), vr.end(),sort(vr.begin(), vr.end(),[] (const Rec& a, const Rec& b)[] (const Rec& a, const Rec& b){ return 0 < strncmp(a.addr, b.addr, 24); } // { return 0 < strncmp(a.addr, b.addr, 24); } // sort bysort by addr addr););

3131Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 31: 20 Containers

Policy parameterizationPolicy parameterization Use a named object as argumentUse a named object as argument

If you want to do something complicatedIf you want to do something complicated If you feel the need for a commentIf you feel the need for a comment If you want to do the same in several placesIf you want to do the same in several places

Use a lambda expression as argumentUse a lambda expression as argument If what you want is short and obviousIf what you want is short and obvious

Choose based on clarity of codeChoose based on clarity of code There are no performance differences between function objects and lambdasThere are no performance differences between function objects and lambdas Function objects (and lambdas) tend to be faster than function argumentsFunction objects (and lambdas) tend to be faster than function arguments

3232Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 32: 20 Containers

vectorvectortemplate<class T> class vector {template<class T> class vector {

T* elements;T* elements;// // ……using value_type = T;using value_type = T;using iterator = ???;using iterator = ???; // // the type of an iterator is implementation definedthe type of an iterator is implementation defined// // and it (usefully) varies (e.g. range checked iterators)and it (usefully) varies (e.g. range checked iterators)// // a vector iterator could be a pointer to an elementa vector iterator could be a pointer to an elementusing const_iterator = ???;using const_iterator = ???;

iterator begin();iterator begin(); // // points to first elementpoints to first elementconst_iterator begin() const; const_iterator begin() const; iterator end();iterator end(); // // points to one beyond the last elementpoints to one beyond the last elementconst_iterator end() const;const_iterator end() const;

iterator erase(iterator p);iterator erase(iterator p); // // remove element pointed to byremove element pointed to by p piterator insert(iterator p, const T& v);iterator insert(iterator p, const T& v); // // insert a new element insert a new element vv before before p p

};};

3333Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 33: 20 Containers

insert() into vectorinsert() into vectorvector<int>::iterator p = v.begin(); ++p; ++p; ++p;vector<int>::iterator p = v.begin(); ++p; ++p; ++p;vector<int>::iterator q = p; ++q;vector<int>::iterator q = p; ++q;

3434

6

0 21 3 4 5

v:

p=v.insert(p,99);p=v.insert(p,99); // // leavesleaves p p pointing at the inserted elementpointing at the inserted element

p:

7

0 21 99 3 4

v:p:

5

q:

q:

Note: q is invalid after theNote: q is invalid after the insert() insert() Note: Some elements moved; all elements could have moved Note: Some elements moved; all elements could have moved

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 34: 20 Containers

erase() from vectorerase() from vector

3535

p = v.erase(p);p = v.erase(p); // // leavesleaves p p pointing at the element after the erased onepointing at the element after the erased one

vector elements move when you insert() or erase()vector elements move when you insert() or erase() Iterators into a vector are invalidated by insert() and erase()Iterators into a vector are invalidated by insert() and erase()

7

0 21 99 3 4

v:p:

5

q:

6

0 21 3 4 5

v:p: q:

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 35: 20 Containers

listlisttemplate<class T> class list {template<class T> class list {

Link* elements;Link* elements;// // ……using value_type = T;using value_type = T;using iterator = ???;using iterator = ???; // // the type of an iterator is implementation definedthe type of an iterator is implementation defined// // and it (usefully) varies (e.g. range checked iterators)and it (usefully) varies (e.g. range checked iterators)// // a list iterator could be a pointer to a link nodea list iterator could be a pointer to a link nodeusing const_iterator = ???;using const_iterator = ???;

iterator begin();iterator begin(); // // points to first elementpoints to first elementconst_iterator begin() const; const_iterator begin() const; iterator end();iterator end(); // // points one beyond the last elementpoints one beyond the last elementconst_iterator end() const;const_iterator end() const;

iterator erase(iterator p);iterator erase(iterator p); // // remove element pointed to byremove element pointed to by p piterator insert(iterator p, const T& v);iterator insert(iterator p, const T& v); // // insert a new element insert a new element vv before before p p

};};

3636

T value

Link* preLink* post

Link:

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 36: 20 Containers

insert() into listinsert() into listlist<int>::iterator p = v.begin(); ++p; ++p; ++p;list<int>::iterator p = v.begin(); ++p; ++p; ++p;list<int>::iterator q = p; ++q;list<int>::iterator q = p; ++q;

3737

7

0 21 3 4 5

v:

v = v.insert(p,99); // leaves p pointing at the inserted element

p:

99

6

0 21 3 4 5

v: p: q:

q:

Note: q is unaffected Note: No elements moved around

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 37: 20 Containers

erase() from listerase() from list

3838

7

0 21 3 4 5

v:

p = v.erase(p); // leaves p pointing at the element after the erased one

p:

99

6

0 21 3 4 5

v:p:

Note: list elements do not move when you insert() or erase()

q:

q:

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 38: 20 Containers

Ways of traversing a vectorWays of traversing a vectorfor(int i = 0; i<v.size(); ++i)for(int i = 0; i<v.size(); ++i) // // why int?why int?

… … // // do something with v[i]do something with v[i]

for(vector<T>::size_type i = 0; i<v.size(); ++i)for(vector<T>::size_type i = 0; i<v.size(); ++i) // // longer but always correctlonger but always correct… … // // do something with v[i]do something with v[i]

for(vector<T>::iterator p = v.begin(); p!=v.end(); ++p)for(vector<T>::iterator p = v.begin(); p!=v.end(); ++p)…… // // do something with *pdo something with *p

Know both ways (iterator and subscript)Know both ways (iterator and subscript) The subscript style is used in essentially every languageThe subscript style is used in essentially every language The iterator style is used in C (pointers only) and C++The iterator style is used in C (pointers only) and C++ The iterator style is used for standard library algorithmsThe iterator style is used for standard library algorithms The subscript style doesn’The subscript style doesn’t work for lists (in C++ and in most languages)t work for lists (in C++ and in most languages)

Use either way for vectorsUse either way for vectors There are no fundamental advantages of one style over the otherThere are no fundamental advantages of one style over the other But the iterator style works for all sequencesBut the iterator style works for all sequences Prefer Prefer size_typesize_type over plain over plain intint

pedantic, but quiets compiler and prevents rare errorspedantic, but quiets compiler and prevents rare errors

3939Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 39: 20 Containers

Ways of traversing a vectorWays of traversing a vectorfor(vector<T>::iterator p = v.begin(); p!=v.end(); ++p)for(vector<T>::iterator p = v.begin(); p!=v.end(); ++p)

…… // // do something with *pdo something with *p

for(vector<T>::value_type x : v)for(vector<T>::value_type x : v)…… // // do something with xdo something with x

for(auto& x : v)for(auto& x : v)…… // // do something with xdo something with x

““Range Range forfor”” Use for the simplest loopsUse for the simplest loops

Every element from Every element from begin() begin() to to end()end() Over one sequenceOver one sequence When you don’t need to look at more than one element at a timeWhen you don’t need to look at more than one element at a time When you don’t need to know the position of an elementWhen you don’t need to know the position of an element

4040Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 40: 20 Containers

Vector vs. ListVector vs. List By default, use a By default, use a vectorvector

You need a reason not toYou need a reason not to You can You can ““growgrow”” a vector (e.g., using a vector (e.g., using push_back()push_back())) You can You can insert() insert() and and erase() erase() in a vectorin a vector Vector elements are compactly stored and contiguousVector elements are compactly stored and contiguous For small vectors of small elements all operations are fastFor small vectors of small elements all operations are fast

compared to listscompared to lists

If you donIf you don’’t want elements to move, use a t want elements to move, use a listlist You can You can ““growgrow”” a list (e.g., using a list (e.g., using push_back() push_back() and and push_front()push_front())) You can You can insert() insert() and and erase() erase() in a listin a list List elements are separately allocatedList elements are separately allocated

Note that there are more containers, e.g.,Note that there are more containers, e.g., mapmap unordered_mapunordered_map

Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13 4141

Page 41: 20 Containers

Some useful standard headersSome useful standard headers <iostream><iostream> I/O streams, cout, cin, …I/O streams, cout, cin, … <fstream><fstream> file streamsfile streams <algorithm><algorithm> sort, copy, …sort, copy, … <numeric><numeric> accumulate, inner_product, …accumulate, inner_product, … <functional><functional> function objectsfunction objects <string><string> <vector><vector> <map><map> <unordered_map><unordered_map> hash tablehash table <list><list> <set><set>

4242Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13

Page 42: 20 Containers

Next lectureNext lecture Map, set, and algorithmsMap, set, and algorithms

4343Stroustrup/Programming - Nov'13Stroustrup/Programming - Nov'13