Top Banner
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
33

Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

Mar 26, 2015

Download

Documents

Autumn Price
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

Chapter 21Chapter 21The STLThe STL

(maps and algorithms)(maps and algorithms)

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

Page 2: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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 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'10Stroustrup/Programming Nov'10

Page 3: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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 “iterator operations” ofAn iterator is a type that supports the “iterator operations” of ++ Point to the next element++ Point to the next element * Get the element* Get the element == 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'10Stroustrup/Programming Nov'10

Page 4: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

template<class In, class T> T accumulate(In first, In last, T init)template<class In, class T> 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'10Stroustrup/Programming Nov'10

Page 5: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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'10Stroustrup/Programming Nov'10

Page 6: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

// // we don’t need to use only +, we can use any binary operation (e.g., *)we don’t need to use only +, we can use any binary operation (e.g., *)//// any function that “updates the any function that “updates the initinit value” can be used: value” 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 “init op *first”means “init op *first”++first;++first;

}}return init;return init;

}}

77Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 7: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

AccumulateAccumulate

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

#include <numeric>#include <numeric>

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'10Stroustrup/Programming Nov'10

Page 8: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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 “update the let the “update the initinit value” function extract data from a value” 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, map<string,Record*>& m) {void f(const vector<Record>& vr, map<string,Record*>& m) {double total = accumulate(vr.begin(), vr.end(), 0.0, price);double total = accumulate(vr.begin(), vr.end(), 0.0, price);// // ……

}}

99Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 9: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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;

}}

1010

1 32

4 3

4

12 * * * *

…number of units

* unit price

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

Page 10: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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);

1111Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 11: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

// // we can supply our own operations for combining element values with“we 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;

}}

1212Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 12: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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) pairsstring s;string s;while (cin>>s) ++words[s];while (cin>>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

00typedef map<string,int>::const_iterator Iter;typedef map<string,int>::const_iterator Iter;for (Iter p = words.begin(); p != words.end(); ++p)for (Iter p = words.begin(); p != words.end(); ++p)

cout << p->first << cout << p->first << "": : "" << p->second << << p->second << ""\n\n"";;}}

1313

Key typeValue type

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

Page 13: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

1414Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 14: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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““policies”.: 1policies”.: 1

1515Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 15: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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;;

1616

Orange 99

Plum 8Kiwi 2345Apple 7

Quince 0Grape 100

fruits:

Key firstValue second

Node* leftNode* right

Map node:

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

Page 16: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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 {// // ……typedef pair<Key,Value> value_type;typedef pair<Key,Value> value_type; // // a map deals in (Key,Value) pairsa map deals in (Key,Value) pairs

typedef ??? iterator;typedef ??? iterator; // // probably a pointer to a tree nodeprobably a pointer to a tree nodetypedef ??? const_iterator;typedef ??? 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&);

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 a new pair insert a new pair beforebefore p p// // ……

};};1717

Some implementation defined type

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

Page 17: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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.html

dow[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 does hold really 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.";// // ……

1818Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 18: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

double alcoa_price = dow["AAA"];double alcoa_price = dow["AAA"]; // // 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:typedef map<string,double>::const_iterator Dow_iterator;typedef map<string,double>::const_iterator Dow_iterator;

for (Dow_iterator p = dow.begin(); p!=dow.end(); ++p) {for (Dow_iterator p = dow.begin(); p!=dow.end(); ++p) {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'';;

}}

1919Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 19: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

2020Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 20: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

Containers and “almost containers”Containers and “almost containers”

Sequence containersSequence containers vector, list, dequevector, list, deque

Associative containersAssociative containers map, set, multimap, multisetmap, set, multimap, multiset

““almost containers”almost containers” array, array, string, stack, queue, priority_queuestring, stack, queue, priority_queue

Soon-to-become standard containersSoon-to-become 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 (Chapters 16-19,22.6)Stroustrup: The C++ Programming language (Chapters 16-19,22.6) Austern: Generic Programming and the STLAustern: Generic Programming and the STL Josuttis: The C++ Standard LibraryJosuttis: The C++ Standard Library

2121Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 21: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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 “failure” by returning the end of a sequenceUsually reports “failure” by returning the end of a sequence

2222Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 22: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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) so that p(x)r points to the first element x in [b,e) so that 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) so that p(x)x is the number of elements in [b,e) so that 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

don’t copy adjacent duplicatesdon’t 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) does all elements of [b,e) and [b2,b2+(e-b)) compare does all elements of [b,e) and [b2,b2+(e-b)) compare

equal?equal?

2323Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 23: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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; ++first

return 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());// // ……

}} 2424Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 24: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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 operation”“get 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 operation”“get ready for the next input operation”string s2 = *ii;string s2 = *ii; // // meaning meaning cin>>s2cin>>s2

2525Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 25: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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 get source and target file

namesnames

ifstream is(from.c_str()); ifstream is(from.c_str()); // // open input streamopen input stream ofstream os(to.c_str());ofstream os(to.c_str()); // // 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}}

2626Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 26: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

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

2727Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 27: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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““policies”.policies”. 2828Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 28: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

We are doing a lot of work that we don’t really needWe are doing a lot of work that we don’t 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

2929Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 29: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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 get source and target file

namesnames

ifstream is(from.c_str()); ifstream is(from.c_str()); // // make input streammake input stream ofstream os(to.c_str());ofstream os(to.c_str()); // // 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 keys3030Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 30: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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;;

3131

Orange

PlumKiwiApple

QuinceGrape

fruits:

Key first

Node* leftNode* right

set node:

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

Page 31: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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;

}}

3232Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 32: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

copy_if()copy_if()

template<class T> struct Less_than {template<class T> struct Less_than {// // “typical” predicate carrying data“typical” predicate carrying data// // this is what you can’t do simply/elegantly with a functionthis is what you can’t do simply/elegantly with a functionT val;T val;Less_than(const T& v) :val(v) { }Less_than(const T& v) :val(v) { }bool operator()(const T& v) const { return v < val; }bool operator()(const T& v) const { return v < val; }

};};

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(), Less_than<int>(6));copy_if(v.begin(), v.end(), v2.begin(), Less_than<int>(6));// // ……

}} 3333Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10

Page 33: Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup .

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

3434Stroustrup/Programming Nov'10Stroustrup/Programming Nov'10