Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

38
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

Transcript of Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

Page 1: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

Chapter 20 Chapter 20 The STLThe STL

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

Bjarne StroustrupBjarne Stroustrupwww.stroustrup.com/Programmingwww.stroustrup.com/Programming

Page 2: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 3: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 4: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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’t that different from using a isn’t that different from using a doubledouble Using a Using a vector<int>vector<int> isn’t that different from using a isn’t that different from using a

vector<string>vector<string>

55Stroustrup/ProgrammingStroustrup/Programming

Page 5: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

IdealsIdeals

We’d like to write common programming tasks so that We’d like to write common programming tasks so that we don’t have to re-do the work each time we find a we don’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’t all that different from isn’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’t all that different ignoring case isn’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 isn’t all that Graphing experimental data with exact values isn’t all that

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

66Stroustrup/ProgrammingStroustrup/Programming

Page 6: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

Ideals Ideals (continued)(continued)

Code that’sCode that’s 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/ProgrammingStroustrup/Programming

Page 7: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 8: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 “Petersen”?Find the first value larger than “Petersen”? 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 pair wise product of the elements of two sequencesCompute the pair wise product of the elements of two sequences What’s the highest temperatures for each day in a month?What’s the highest temperatures for each day in a month? What’s the top 10 best-sellers?What’s the top 10 best-sellers? What’s the entry for “C++” (say, in Google)?What’s the entry for “C++” (say, in Google)? What’s the sum of the elements?What’s the sum of the elements?

99Stroustrup/ProgrammingStroustrup/Programming

Page 9: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

1010

Generic programmingGeneric programming Generalize algorithmsGeneralize algorithms

Sometimes called “lifting an algorithm”Sometimes called “lifting 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

Page 10: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

1111

Lifting example Lifting example (concerte algorithms)(concerte algorithms)

double sum(double array[], int n)double sum(double array[], int n) // // one concrete algorithm (doubles in one concrete algorithm (doubles in array)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) {

s += first->data;s += first->data;first = first->next;first = first->next;

}}return s;return s;

}}

Page 11: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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

Page 12: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 “accumulator type”T is the “accumulator 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);

Page 13: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 “hand-crafted” codeRuns as fast as “hand-crafted” code Given decent inliningGiven decent inlining

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

Page 14: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 15: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 “like math”General aim to make programming “like math” or even “Good programming or even “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/ProgrammingStroustrup/Programming

Page 16: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

Basic modelBasic model AlgorithmsAlgorithms

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

ContainersContainers vector, list, map, hash_map, …vector, list, map, hash_map, …

1717

iterators

• Separation of concernsSeparation of concerns– Algorithms manipulate Algorithms manipulate

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

– Containers store data, but Containers store data, but don’t know about don’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/ProgrammingStroustrup/Programming

Page 17: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 18: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 19: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

Basic modelBasic model A pair of iterators define a sequenceA pair of iterators define 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 “iterator operations”An iterator is a type that supports the “iterator 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/ProgrammingStroustrup/Programming

Page 20: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 21: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 (“abstract away”) the differences between containersWe can ignore (“abstract away”) the differences between containersStroustrup/ProgrammingStroustrup/Programming

Page 22: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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>::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 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>::iterator p = find(v.begin(),v.end(),x);list<string>::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 of works of setset of of doubledoubless{{

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

}}2323Stroustrup/ProgrammingStroustrup/Programming

Page 23: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 “one past the last element”The end of the sequence is “one past the last element”

notnot “the last element” “the last element” That’s necessary to elegantly represent an empty sequenceThat’s necessary to elegantly represent an empty sequence One-past-the-last-element isn’t an elementOne-past-the-last-element isn’t an element

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

Returning the end of the sequence is the standard idiom for “not Returning the end of the sequence is the standard idiom for “not found” or “unsuccessful”found” or “unsuccessful”

2424

0 1 2 3

the end:An empty sequence:some

iterator:

Stroustrup/ProgrammingStroustrup/Programming

Page 24: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

Simple algorithm: Simple algorithm: find_if()find_if() Find the first element that match a criterion (predicate)Find the first element that match 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/ProgrammingStroustrup/Programming

Page 25: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 26: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 with

Less_than(int x) :val(x) { }Less_than(int 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/ProgrammingStroustrup/Programming

Page 27: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 can’t write an equivalent functionAnd sometimes you can’t 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/ProgrammingStroustrup/Programming

Page 28: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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 “policy”.parameterize it by a “policy”. 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 use

char 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 name

sort(vr.begin(), vr.end(), Cmp_by_addr());sort(vr.begin(), vr.end(), Cmp_by_addr()); // // sort bysort by addr addr

2929Stroustrup/ProgrammingStroustrup/Programming

Page 29: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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/ProgrammingStroustrup/Programming

Page 30: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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

T* elements;T* elements;// // ……typedef ??? iterator;typedef ??? iterator; // // the type of an iterator is implementation definedthe type of an iterator is implementation defined

// // and it (usefully) varies (e.g. range checked and it (usefully) varies (e.g. range checked iterators)iterators)

// // a vector iterator could be a pointer to an elementa vector iterator could be a pointer to an elementtypedef ??? const_iterator;typedef ??? 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

};};

3131Stroustrup/ProgrammingStroustrup/Programming

Page 31: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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;

3232

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/ProgrammingStroustrup/Programming

Page 32: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

erase() from vectorerase() from vector

3333

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/ProgrammingStroustrup/Programming

Page 33: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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

Link* elements;Link* elements;// // ……typedef ??? iterator;typedef ??? 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 node

typedef ??? const_iterator;typedef ??? 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

};};

3434

T value

Link* preLink* post

Link:

Stroustrup/ProgrammingStroustrup/Programming

Page 34: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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;

3535

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/ProgrammingStroustrup/Programming

Page 35: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

erase() from listerase() from list

3636

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/ProgrammingStroustrup/Programming

Page 36: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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<int>::size_type i = 0; i<v.size(); ++i)for(vector<int>::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<int>::iterator p = v.begin(); p!=v.end(); ++p)for(vector<int>::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’t work for lists (in C++ and in most languages)The subscript style doesn’t work for lists (in C++ and in most languages)

use either way for vectorsuse either way for vectors There are no fundamental advantage of one style over the otherThere are no fundamental advantage 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

3737Stroustrup/ProgrammingStroustrup/Programming

Page 37: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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> <list><list> <set><set>

3838Stroustrup/ProgrammingStroustrup/Programming

Page 38: Chapter 20 The STL (containers, iterators, and algorithms) Bjarne Stroustrup .

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

3939Stroustrup/ProgrammingStroustrup/Programming