36
Chapter 21 Chapter 21 The STL The STL (maps and algorithms) (maps and algorithms) Bjarne Stroustrup Bjarne Stroustrup www.stroustrup.com/Programming www.stroustrup.com/Programming

[PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

  • Upload
    vohanh

  • View
    220

  • Download
    0

Embed Size (px)

Citation preview

Page 1: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Chapter 21Chapter 21The STLThe STL

(maps and algorithms)(maps and algorithms)

Bjarne StroustrupBjarne Stroustrup

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

Page 2: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

OverviewOverview Common tasks and idealsCommon tasks and ideals 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 Algorithms and parameterization revisitedAlgorithms and parameterization revisited 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: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

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)

44

begin: end:

An iterator is a type that supports the An iterator is a type that supports the ““iterator operationsiterator operations”” of of ++ Point to the next element++ Point to the next element * Get the element value* Get the element 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 Some iterators support more operations (e.g(e.g., --, +, and [ ])., --, +, and [ ])Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 4: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Accumulate Accumulate (sum the elements of a sequence)(sum the elements of a sequence)

template<class In, class T>template<class In, class T>T accumulate(In first, In last, T init)T accumulate(In first, In last, T init){{

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

}}

55

1 432v:

int sum = accumulate(v.begin(), v.end(), 0); // int sum = accumulate(v.begin(), v.end(), 0); // sum sum becomes 10becomes 10

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

Page 5: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Accumulate Accumulate (sum the elements of a sequence)(sum the elements of a sequence)

void f(vector<double>& vd, int* p, int n)void f(vector<double>& vd, int* p, int n){{

double sum = accumulate(vd.begin(), vd.end(), 0.0); // double sum = accumulate(vd.begin(), vd.end(), 0.0); // add the elements of add the elements of vdvd// // note: the type of the 3note: the type of the 3rdrd argument, the initializer, determines the precision used argument, the initializer, determines the precision used

int si = accumulate(p, p+n, 0);int si = accumulate(p, p+n, 0); // // sum the sum the intints in an s in an intint (danger of overflow) (danger of overflow) // // p+n p+n means (roughly)means (roughly) &p[n] &p[n]

long sl = accumulate(p, p+n, long(0));long sl = accumulate(p, p+n, long(0)); // // sum thesum the int intss in ain a long longdouble s2 = accumulate(p, p+n, 0.0);double s2 = accumulate(p, p+n, 0.0); // // sum thesum the int intss in ain a double double

// // popular idiom, use the variable you want the result in as the initializer:popular idiom, use the variable you want the result in as the initializer:double ss = 0;double ss = 0;ss = accumulate(vd.begin(), vd.end(), ss); // ss = accumulate(vd.begin(), vd.end(), ss); // do remember the assignmentdo remember the assignment

}}66Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 6: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

AccumulateAccumulate(generalize: process the elements of a sequence)(generalize: process the elements of a sequence)

// // we donwe don’’t need to use only +, we can use any binary operation (e.g., *)t need to use only +, we can use any binary operation (e.g., *)//// any function that any function that ““updates the updates the initinit value value”” can be used: can be used:

template<class In, class T, class BinOp>template<class In, class T, class BinOp>T accumulate(In first, In last, T init, BinOp op)T accumulate(In first, In last, T init, BinOp op){{

while (first!=last) {while (first!=last) {init = op(init, *first);init = op(init, *first); // // means means ““init op *firstinit op *first””++first;++first;

}}return init;return init;

}}

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

Page 7: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

AccumulateAccumulate

// // often, we need multiplication rather than addition:often, we need multiplication rather than addition:

#include <numeric>#include <numeric>#include <functional>#include <functional>void f(list<double>& ld)void f(list<double>& ld){{

double product = accumulate(ld.begin(), ld.end(), 1.0, multiplies<double>());double product = accumulate(ld.begin(), ld.end(), 1.0, multiplies<double>());// // ……

}}

// // multiplies multiplies is a standard library function object for multiplyingis a standard library function object for multiplying

88

Note: multiplies for *

Note: initializer 1.0

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

Page 8: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Accumulate Accumulate (what if the data is part of a record?)(what if the data is part of a record?)

struct Record {struct Record {int units;int units; // // number of units soldnumber of units solddouble unit_price;double unit_price;// // ……

};};

// // let the let the ““update the update the initinit value value”” function extract data from a function extract data from a Record Record element:element:double price(double v, const Record& r)double price(double v, const Record& r){ {

return v + r.unit_price * r.units;return v + r.unit_price * r.units;}}

void f(const vector<Record>& vr) {void f(const vector<Record>& vr) {double total = accumulate(vr.begin(), vr.end(), 0.0, price);double total = accumulate(vr.begin(), vr.end(), 0.0, price);// // ……

}}

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

Page 9: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Accumulate Accumulate (what if the data is part of a record?)(what if the data is part of a record?)

struct Record {struct Record {int units;int units; // // number of units soldnumber of units solddouble unit_price;double unit_price;// // ……

};};

void f(const vector<Record>& vr) {void f(const vector<Record>& vr) {double total = accumulate(vr.begin(), vr.end(), 0.0, // double total = accumulate(vr.begin(), vr.end(), 0.0, // use a lambdause a lambda

[](double v, const Record& r)[](double v, const Record& r){ return v + r.unit_price * r.units; }{ return v + r.unit_price * r.units; }

););// // ……

}}

// // Is this clearer or less clear than the price() function?Is this clearer or less clear than the price() function?

1010Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 10: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Inner productInner product

template<class In, class In2, class T>template<class In, class In2, class T>T inner_product(In first, In last, In2 first2, T init)T inner_product(In first, In last, In2 first2, T init)

// // This is the way we multiply two vectors (yielding a scalar)This is the way we multiply two vectors (yielding a scalar){{

while(first!=last) {while(first!=last) { init = init + (*first) * (*first2); // init = init + (*first) * (*first2); // multiply pairs of elements and summultiply pairs of elements and sum ++first;++first; ++first2;++first2;

}}return init;return init;

}}

1111

1 32

4 3

4

12 * * * *

…number of units

* unit price

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

Page 11: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Inner product exampleInner product example// // calculate the Dow-Jones industrial index:calculate the Dow-Jones industrial index:vector<double> dow_price;vector<double> dow_price; // // share price for each companyshare price for each companydow_price.push_back(81.86); dow_price.push_back(81.86); dow_price.push_back(34.69);dow_price.push_back(34.69);dow_price.push_back(54.45);dow_price.push_back(54.45);// // ……vector<double> dow_weight; vector<double> dow_weight; // // weight in index for each companyweight in index for each companydow_weight.push_back(5.8549);dow_weight.push_back(5.8549);dow_weight.push_back(2.4808);dow_weight.push_back(2.4808);dow_weight.push_back(3.8940);dow_weight.push_back(3.8940);// // ……double dj_index = inner_product( // double dj_index = inner_product( // multiply (price,weight) pairs and addmultiply (price,weight) pairs and add

dow_price.begin(), dow_price.end(),dow_price.begin(), dow_price.end(),dow_weight.begin(),dow_weight.begin(),0.0);0.0);

1212Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 12: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Inner product exampleInner product example// // calculate the Dow-Jones industrial index:calculate the Dow-Jones industrial index:vector<double> dow_price = {vector<double> dow_price = { // // share price for each companyshare price for each company

81.86, 34.69, 54.45,81.86, 34.69, 54.45,// // ……

};};vector<double> dow_weight = { vector<double> dow_weight = { // // weight in index for each companyweight in index for each company

5.8549, 2.4808, 3.8940,5.8549, 2.4808, 3.8940,// // ……

};};

double dj_index = inner_product( // double dj_index = inner_product( // multiply (price,weight) pairs and addmultiply (price,weight) pairs and adddow_price.begin(), dow_price.end(),dow_price.begin(), dow_price.end(),dow_weight.begin(),dow_weight.begin(),0.0);0.0);

1313Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 13: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Inner product Inner product (generalize!)(generalize!)

// // we can supply our own operations for combining element values withwe can supply our own operations for combining element values with““initinit””::template<class In, class In2, class T, class BinOp, class BinOp2 >template<class In, class In2, class T, class BinOp, class BinOp2 >T inner_product(In first, In last, In2 first2, T init, BinOp op, BinOp2 op2)T inner_product(In first, In last, In2 first2, T init, BinOp op, BinOp2 op2){{

while(first!=last) {while(first!=last) {init = op(init, op2(*first, *first2));init = op(init, op2(*first, *first2));++first;++first;++first2;++first2;

}}return init;return init;

}}

1414Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 14: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Map Map (an associative array)(an associative array)

For a For a vectorvector, you subscript using an integer, you subscript using an integer For a For a mapmap, you can define the subscript to be (just about) any type, you can define the subscript to be (just about) any type

int main()int main(){{

map<string,int> words;map<string,int> words; // // keep (word,frequency) pairskeep (word,frequency) pairsfor (for (string s; cin>>s; )string s; cin>>s; )

++words[s];++words[s]; // // note:note: words words is subscripted by is subscripted by aa string string

// // words[s] words[s] returns anreturns an int& int&// // thethe int int values are initialized to values are initialized to

00for (const auto& p : words)for (const auto& p : words)

cout << p.first << cout << p.first << "": : "" << p.second << << p.second << ""\n\n"";;}}

1515

Key typeValue type

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

Page 15: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

An input for the words program An input for the words program (the abstract) (the abstract)

This lecture and the next presents the STL (the containers and algorithms part This lecture and the next presents the STL (the containers and algorithms part of the C++ standard library). It is an extensible framework dealing with of the C++ standard library). It is an extensible framework dealing with data in a C++ program. First, I present the general ideal, then the data in a C++ program. First, I present the general ideal, then the fundamental concepts, and finally examples of containers and algorithms. fundamental concepts, and finally examples of containers and algorithms. The key notions of sequence and iterator used to tie containers (data) The key notions of sequence and iterator used to tie containers (data) together with algorithms (processing) are presented. Function objects are together with algorithms (processing) are presented. Function objects are used to parameterize algorithms with “policies”.used to parameterize algorithms with “policies”.

1616Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 16: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Output Output (word frequencies)(word frequencies)(data): 1(data): 1(processing): 1(processing): 1(the: 1(the: 1C++: 2C++: 2First,: 1First,: 1Function: 1Function: 1I: 1I: 1It: 1It: 1STL: 1STL: 1The: 1The: 1This: 1This: 1a: 1a: 1algorithms: 3algorithms: 3algorithms.: 1algorithms.: 1an: 1an: 1and: 5and: 5are: 2are: 2concepts,: 1concepts,: 1containers: 3containers: 3data: 1data: 1dealing: 1dealing: 1examples: 1examples: 1extensible: 1extensible: 1finally: 1finally: 1framework: 1framework: 1fundamental: 1fundamental: 1general: 1general: 1ideal,: 1ideal,: 1in: 1in: 1is: 1is: 1

iterator: 1iterator: 1key: 1key: 1lecture: 1lecture: 1library).: 1library).: 1next: 1next: 1notions: 1notions: 1objects: 1objects: 1of: 3of: 3parameterize: 1parameterize: 1part: 1part: 1present: 1present: 1presented.: 1presented.: 1presents: 1presents: 1program.: 1program.: 1sequence: 1sequence: 1standard: 1standard: 1the: 5the: 5then: 1then: 1tie: 1tie: 1to: 2to: 2together: 1together: 1used: 2used: 2with: 3with: 3““policiespolicies””.: 1.: 1

1717Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 17: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Map Map (an associative array)(an associative array)

For a For a vectorvector, you subscript using an integer, you subscript using an integer For a For a mapmap, you can define the subscript to be (just about) any type, you can define the subscript to be (just about) any type

int main()int main(){{

map<string,int> words;map<string,int> words; // // keep (word,frequency) pairskeep (word,frequency) pairsfor (for (string s; cin>>s; )string s; cin>>s; )

++words[s];++words[s]; // // note:note: words words is subscripted by is subscripted by aa string string

// // words[s] words[s] returns anreturns an int& int&// // thethe int int values are initialized to values are initialized to

00for (const auto& p : words)for (const auto& p : words)

cout << p.first << cout << p.first << "": : "" << p.second << << p.second << ""\n\n"";;}}

1818

Key typeValue type

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

Page 18: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

MapMap After After vectorvector, , mapmap is the most useful standard library container is the most useful standard library container

Maps (and/or hash tables) are the backbone of scripting languages Maps (and/or hash tables) are the backbone of scripting languages A A mapmap is really an ordered balanced binary tree is really an ordered balanced binary tree

By default ordered by By default ordered by < < (less than)(less than) For example, For example, map<string,int> fruitsmap<string,int> fruits;;

1919

Orange 99

Plum 8Kiwi 2345Apple 7

Quince 0Grape 100

fruits:

Key firstValue second

Node* leftNode* right

Map node:

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

Page 19: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

MapMap// // note the similarity tonote the similarity to vector vector and and listlist

template<class Key, class Value> class map {template<class Key, class Value> class map {// // ……using value_type = pair<Key,Value>;using value_type = pair<Key,Value>; // // a map deals in (Key,Value) pairsa map deals in (Key,Value) pairs

using iterator = ???; // using iterator = ???; // probably a pointer to a tree nodeprobably a pointer to a tree nodeusing const_iterator = ???;using const_iterator = ???;

iterator begin();iterator begin(); // // points to first elementpoints to first elementiterator end();iterator end(); // // points to one beyond the last elementpoints to one beyond the last element

Value& operator[ ](const Key&);Value& operator[ ](const Key&); // // get Value for Key; creates pair ifget Value for Key; creates pair if // // necessary, using Value( )necessary, using Value( )

iterator find(const Key& k);iterator find(const Key& k); // // is there an entry foris there an entry for k? k?

void erase(iterator p);void erase(iterator p); // // remove element pointed to byremove element pointed to by p ppair<iterator, bool> insert(const value_type&); // pair<iterator, bool> insert(const value_type&); // insert new (Key,Value) pair insert new (Key,Value) pair // // …… // // thethe bool is false if insert bool is false if insert failedfailed

};};2020

Some implementation defined type

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

Page 20: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Map example Map example (build some maps)(build some maps)map<string,double> dow;map<string,double> dow; // // Dow-Jones industrial index (symbol,price) , 03/31/2004Dow-Jones industrial index (symbol,price) , 03/31/2004

// // http://www.djindexes.com/jsp/industrialAverages.jsp?sideMenu=true.htmlhttp://www.djindexes.com/jsp/industrialAverages.jsp?sideMenu=true.htmldow[dow[""MMM"] = 81.86; MMM"] = 81.86; dow["AA"] = 34.69;dow["AA"] = 34.69;dow["MO"] = 54.45;dow["MO"] = 54.45;// // ……map<string,double> dow_weight;map<string,double> dow_weight; // // dow (symbol,weight)dow (symbol,weight)dow_weight.insert(make_pair("MMM", 5.8549));dow_weight.insert(make_pair("MMM", 5.8549)); // // just to show that a just to show that a MapMap //// really really

does hold does hold pairpairssdow_weight.insert(make_pair("AA",2.4808));dow_weight.insert(make_pair("AA",2.4808));dow_weight.insert(make_pair("MO",3.8940));dow_weight.insert(make_pair("MO",3.8940)); // // and to show that notation mattersand to show that notation matters// // ……map<string,string> dow_name;map<string,string> dow_name;// // dow (symbol,name)dow (symbol,name)dow_name["MMM"] = "3M Co."; dow_name["MMM"] = "3M Co."; dow_name["AA"] = "Alcoa Inc.";dow_name["AA"] = "Alcoa Inc.";dow_name["MO"] = "Altria Group Inc.";dow_name["MO"] = "Altria Group Inc.";// // ……

2121Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 21: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Map example Map example (some uses)(some uses)

double alcoa_price = dow["AA"];double alcoa_price = dow["AA"]; // // read values from a mapread values from a mapdouble boeing_price = dow["BO"];double boeing_price = dow["BO"];

if (dow.find("INTC") != dow.end())if (dow.find("INTC") != dow.end()) // // look in a map for an entrylook in a map for an entrycout << "Intel is in the Dow\n";cout << "Intel is in the Dow\n";

// // iterate through a map:iterate through a map:

for (const auto& p : dow) {for (const auto& p : dow) {const string& symbol = p.first;const string& symbol = p.first; // // the "ticker" symbolthe "ticker" symbolcout << symbol << cout << symbol << ''\t\t'' << p.second << << p.second << ''\t\t'' << dow_name[symbol] << << dow_name[symbol] << ''\n\n'';;

}}

2222Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 22: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Map example Map example (calculate the DJ index)(calculate the DJ index)

double value_product(double value_product(const pair<string,double>& a,const pair<string,double>& a,const pair<string,double>& b)const pair<string,double>& b) // // extract values and multiplyextract values and multiply

{{return a.second * b.second;return a.second * b.second;

}}

double dj_index =double dj_index =inner_product(dow.begin(), dow.end(),inner_product(dow.begin(), dow.end(), // // all companies in indexall companies in index

dow_weight.begin(),dow_weight.begin(), // // their weightstheir weights0.0,0.0, // // initial valueinitial valueplus<double>(),plus<double>(), // // add (as usual)add (as usual)value_productvalue_product // // extract values and extract values and

weightsweights);); //// and multiply; then sumand multiply; then sum

2323Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 23: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Containers and Containers and ““almost containersalmost containers”” Sequence containersSequence containers

vector, list, dequevector, list, deque Associative containersAssociative containers

map, set, multimap, multisetmap, set, multimap, multiset ““almost containersalmost containers””

array, array, string, stack, queue, priority_queue, bitsetstring, stack, queue, priority_queue, bitset New C++11 standard containersNew C++11 standard containers

unordered_map unordered_map (a hash table), (a hash table), unordered_set, unordered_set, …… For anything non-trivial, consult documentationFor anything non-trivial, consult documentation

OnlineOnline SGI, RogueWave, DinkumwareSGI, RogueWave, Dinkumware

Other booksOther books Stroustrup: The C++ Programming language 4Stroustrup: The C++ Programming language 4thth ed. (Chapters 30-33, 40.6) ed. (Chapters 30-33, 40.6) Austern: Generic Programming and the STLAustern: Generic Programming and the STL Josuttis: The C++ Standard LibraryJosuttis: The C++ Standard Library

2424Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 24: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

AlgorithmsAlgorithms An STL-style algorithmAn STL-style algorithm

Takes one or more sequencesTakes one or more sequences Usually as pairs of iteratorsUsually as pairs of iterators

Takes one or more operationsTakes one or more operations Usually as function objectsUsually as function objects Ordinary functions also workOrdinary functions also work

Usually reports Usually reports ““failurefailure”” by returning the end of a sequence by returning the end of a sequence

2525Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 25: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Some useful standard algorithmsSome useful standard algorithms

r=find(b,e,v)r=find(b,e,v) r points to the first occurrence of v in [b,e)r points to the first occurrence of v in [b,e) r=find_if(b,e,p)r=find_if(b,e,p) r points to the first element x in [b,e) for which p(x)r points to the first element x in [b,e) for which p(x) x=count(b,e,v)x=count(b,e,v) x is the number of occurrences of v in [b,e)x is the number of occurrences of v in [b,e) x=count_if(b,e,p)x=count_if(b,e,p) x is the number of elements in [b,e) for which p(x)x is the number of elements in [b,e) for which p(x) sort(b,e)sort(b,e) sort [b,e) using <sort [b,e) using < sort(b,e,p)sort(b,e,p) sort [b,e) using psort [b,e) using p copy(b,e,b2)copy(b,e,b2) copy [b,e) to [b2,b2+(e-b))copy [b,e) to [b2,b2+(e-b))

there had better be enough space after b2there had better be enough space after b2 unique_copy(b,e,b2)unique_copy(b,e,b2) copy [b,e) to [b2,b2+(e-b)) butcopy [b,e) to [b2,b2+(e-b)) but

dondon’’t copy adjacent duplicatest copy adjacent duplicates merge(b,e,b2,e2,r)merge(b,e,b2,e2,r) merge two sorted sequence [b2,e2) and [b,e)merge two sorted sequence [b2,e2) and [b,e)

into [r,r+(e-b)+(e2-b2))into [r,r+(e-b)+(e2-b2)) r=equal_range(b,e,v)r=equal_range(b,e,v) r is the subsequence of [b,e) with the value vr is the subsequence of [b,e) with the value v

(basically a binary search for v)(basically a binary search for v) equal(b,e,b2)equal(b,e,b2) do all elements of [b,e) and [b2,b2+(e-b)) compare do all elements of [b,e) and [b2,b2+(e-b)) compare

equal?equal?

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

Page 26: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Copy exampleCopy example

template<class In, class Out> Out copy(In first, In last, Out res)template<class In, class Out> Out copy(In first, In last, Out res){{

while (first!=last) *res++ = *first++;while (first!=last) *res++ = *first++;// // conventional shorthand for:conventional shorthand for:// // *res = *first; ++res; ++first*res = *first; ++res; ++firstreturn res;return res;

}}

void f(vector<double>& vd, list<int>& li)void f(vector<double>& vd, list<int>& li){{

if (vd.size() < li.size()) error("target container too small");if (vd.size() < li.size()) error("target container too small");copy(li.begin(), li.end(), vd.begin());copy(li.begin(), li.end(), vd.begin()); // // note: different container typesnote: different container types// // and different element typesand different element types// // ((vdvd better have enough elements better have enough elements// // to hold copies of to hold copies of lili’’s elements)s elements)sort(vd.begin(), vd.end());sort(vd.begin(), vd.end());// // ……

}} 2727Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 27: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Input and output iteratorsInput and output iterators

// // we can provide iterators for output streamswe can provide iterators for output streams

ostream_iterator<string> oo(cout);ostream_iterator<string> oo(cout); // // assigning toassigning to *oo *oo is to write tois to write to coutcout

*oo = "Hello, ";*oo = "Hello, "; // // meaning meaning cout << "Hello, "cout << "Hello, "++oo;++oo; // // ““get ready for next output operationget ready for next output operation””*oo = "world!\n";*oo = "world!\n"; // // meaning meaning cout << "world!\n"cout << "world!\n"

// // we can provide iterators for input streams:we can provide iterators for input streams:

istream_iterator<string> ii(cin); // istream_iterator<string> ii(cin); // reading reading *ii *ii is to read a is to read a stringstring from from cin cin

string s1 = *ii;string s1 = *ii; // // meaning meaning cin>>s1cin>>s1++ii;++ii; // // ““get ready for the next input operationget ready for the next input operation””string s2 = *ii;string s2 = *ii; // // meaning meaning cin>>s2cin>>s2

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

Page 28: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Make a quick dictionary Make a quick dictionary (using a vector)(using a vector)

int main()int main(){{ string from, to;string from, to; cin >> from >> to; cin >> from >> to; // // get source and target file namesget source and target file names

ifstream is(from); ifstream is(from); // // open input streamopen input stream ofstream os(to);ofstream os(to); // // open output streamopen output stream

istream_iterator<string> ii(is); istream_iterator<string> ii(is); // // make input iterator for streammake input iterator for stream istream_iterator<string> eos; istream_iterator<string> eos; // // input sentinel (defaults to EOF)input sentinel (defaults to EOF) ostream_iterator<string> oo(os,"\n");ostream_iterator<string> oo(os,"\n"); // // make output iterator for streammake output iterator for stream

// // append append "\n""\n" each time each time vector<string> b(ii,eos);vector<string> b(ii,eos); // // b b is ais a vector vector initialized from inputinitialized from input sort(b.begin(),b.end());sort(b.begin(),b.end()); // // sort the buffersort the buffer unique_copy(b.begin(),b.end(),oo); unique_copy(b.begin(),b.end(),oo); // // copy buffer to output,copy buffer to output, // // discard replicated valuesdiscard replicated values}}

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

Page 29: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

An input file An input file (the abstract)(the abstract)

This lecture and the next presents the STL (the containers and algorithms part This lecture and the next presents the STL (the containers and algorithms part of the C++ standard library). It is an extensible framework dealing with of the C++ standard library). It is an extensible framework dealing with data in a C++ program. First, I present the general ideal, then the data in a C++ program. First, I present the general ideal, then the fundamental concepts, and finally examples of containers and algorithms. fundamental concepts, and finally examples of containers and algorithms. The key notions of sequence and iterator used to tie containers (data) The key notions of sequence and iterator used to tie containers (data) together with algorithms (processing) are presented. Function objects are together with algorithms (processing) are presented. Function objects are used to parameterize algorithms with used to parameterize algorithms with ““policiespolicies””..

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

Page 30: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Part of the outputPart of the output(data)(data)(processing)(processing)(the(theC++C++First,First,FunctionFunctionIIItItSTLSTLTheTheThisThisaaalgorithmsalgorithmsalgorithms.algorithms.ananandandareareconcepts,concepts,containerscontainersdatadatadealingdealingexamplesexamplesextensibleextensiblefinallyfinallyFrameworkFrameworkfundamentalfundamentalgeneralgeneralideal,ideal,

ininisisiteratoriteratorkeykeylecturelecturelibrary).library).nextnextnotionsnotionsobjectsobjectsofofparameterizeparameterizepartpartpresentpresentpresented.presented.presentspresentsprogram.program.sequencesequencestandardstandardthethethenthentietietototogethertogetherusedusedwithwith““policiespolicies””..

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

Page 31: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Make a quick dictionary Make a quick dictionary (using a vector)(using a vector)

We are doing a lot of work that we donWe are doing a lot of work that we don’’t really needt really need Why store all the duplicates? (in the vector)Why store all the duplicates? (in the vector) Why sort?Why sort? Why suppress all the duplicates on output?Why suppress all the duplicates on output?

Why not justWhy not just Put each word in the right place in a dictionary as we read it?Put each word in the right place in a dictionary as we read it? In other words: use a In other words: use a setset

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

Page 32: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Make a quick dictionary Make a quick dictionary (using a set)(using a set)

int main()int main(){{ string from, to;string from, to; cin >> from >> to; cin >> from >> to; // // get source and target file namesget source and target file names

ifstream is(from); ifstream is(from); // // make input streammake input stream ofstream os(to);ofstream os(to); // // make output streammake output stream

istream_iterator<string> ii(is); istream_iterator<string> ii(is); // // make input iterator for streammake input iterator for stream istream_iterator<string> eos; istream_iterator<string> eos; // // input sentinel (defaults to EOF)input sentinel (defaults to EOF) ostream_iterator<string> oo(os,"\n");ostream_iterator<string> oo(os,"\n"); // // make output iterator for streammake output iterator for stream

//// append append "\n""\n" each time each time set<string> b(ii,eos);set<string> b(ii,eos); // // b b is ais a set set initialized from inputinitialized from input copy(b.begin(),b.end(),oo); copy(b.begin(),b.end(),oo); // // copy buffer to outputcopy buffer to output}}

// // simple definition: a set is a map with no values, just keyssimple definition: a set is a map with no values, just keys

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

Page 33: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

SetSet

A A setset is really an ordered balanced binary tree is really an ordered balanced binary tree By default ordered by <By default ordered by < For example, For example, set<string> fruitsset<string> fruits;;

3434

Orange

PlumKiwiApple

QuinceGrape

fruits:

Key first

Node* leftNode* right

set node:

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

Page 34: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

copy_if()copy_if()// // a very useful algorithm (missing from the standard library):a very useful algorithm (missing from the standard library):

template<class In, class Out, class Pred>template<class In, class Out, class Pred>Out copy_if(In first, In last, Out res, Pred p)Out copy_if(In first, In last, Out res, Pred p)

// // copy elements that fulfill the predicatecopy elements that fulfill the predicate{{

while (first!=last) {while (first!=last) {if (p(*first)) *res++ = *first;if (p(*first)) *res++ = *first;++first;++first;

}}return res;return res;

}}

3535Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 35: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

copy_if()copy_if()

void f(const vector<int>& v)void f(const vector<int>& v) // // “typical use” of predicate with data“typical use” of predicate with data //// copy all elements with a value less than copy all elements with a value less than

66{{

vector<int> v2(v.size());vector<int> v2(v.size());copy_if(v.begin(), v.end(), v2.begin(),copy_if(v.begin(), v.end(), v2.begin(),

[](int x) { return x<6; } );[](int x) { return x<6; } );// // ……

}}

3636Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13

Page 36: [PPT]PowerPoint Presentation - Bjarne Stroustrup's · Web viewChapter 21 The STL (maps and algorithms) Bjarne Stroustrup Set A set is really an ordered balanced binary tree By default

Some standard function objectsSome standard function objects From <functional>From <functional>

BinaryBinary plus, minus, multiplies, divides, modulusplus, minus, multiplies, divides, modulus equal_to, not_equal_to, greater, less, greater_equal, less_equal, equal_to, not_equal_to, greater, less, greater_equal, less_equal,

logical_and, logical_orlogical_and, logical_or UnaryUnary

negatenegate logical_notlogical_not

Unary (missing, write them yourself)Unary (missing, write them yourself) less_than, greater_than, less_than_or_equal, greater_than_or_equalless_than, greater_than, less_than_or_equal, greater_than_or_equal

3737Stroustrup/Programming Nov'13Stroustrup/Programming Nov'13