an introduction to stl. the c++ standard template libraries in 1990, alex stepanov and meng lee of...

70
An Introduction to STL An Introduction to STL

Upload: leslie-harmon

Post on 05-Jan-2016

229 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

An Introduction to STLAn Introduction to STL

Page 2: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

The C++ Standard The C++ Standard Template LibrariesTemplate Libraries

In 1990, Alex Stepanov and Meng In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Lee of Hewlett Packard Laboratories extended C++ with a Laboratories extended C++ with a library of class and function library of class and function templates which has come to be templates which has come to be known as the STL.known as the STL.

In 1994, STL was adopted as part In 1994, STL was adopted as part of ANSI/ISO Standard C++.of ANSI/ISO Standard C++.

Page 3: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

The C++ Standard The C++ Standard Template LibrariesTemplate Libraries

STL had three basic components:STL had three basic components:• ContainersContainers

Generic class templates for storing collection of data. Generic class templates for storing collection of data. • AlgorithmsAlgorithms

Generic function templates for operating on containers.Generic function templates for operating on containers.• IteratorsIterators

Generalized ‘smart’ pointers that facilitate use of Generalized ‘smart’ pointers that facilitate use of containers.containers.They provide an interface that is needed for STL They provide an interface that is needed for STL algorithms to operate on STL containers.algorithms to operate on STL containers.

String abstraction was added during String abstraction was added during standardization. standardization.

Page 4: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Why use STL?Why use STL?

STL offers an assortment of containersSTL offers an assortment of containers STL publicizes the time and storage complexity STL publicizes the time and storage complexity

of its containersof its containers STL containers grow and shrink in size STL containers grow and shrink in size

automaticallyautomatically STL provides built-in algorithms for processing STL provides built-in algorithms for processing

containerscontainers STL provides iterators that make the containers STL provides iterators that make the containers

and algorithms flexible and efficient.and algorithms flexible and efficient. STL is extensible which means that users can STL is extensible which means that users can

add new containers and new algorithms such add new containers and new algorithms such that:that:• STL algorithms can process STL containers as well as STL algorithms can process STL containers as well as

user defined containersuser defined containers• User defined algorithms can process STL containers as User defined algorithms can process STL containers as

well user defined containers well user defined containers

Page 5: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

StringsStrings

In C we used In C we used char *char * to to represent a string.represent a string.

The C++ standard library The C++ standard library provides a common provides a common implementation of a implementation of a string string classclass abstraction named abstraction named stringstring..

Page 6: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Hello World - CHello World - C

#include <stdio.h>#include <stdio.h>

voidvoid main() main()

{{

// create string ‘str’ = “Hello world!”// create string ‘str’ = “Hello world!”

charchar *str = *str = “Hello World!”;“Hello World!”;

printf(printf(“%s\n”“%s\n”, str);, str);

}}

Page 7: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Hello World – C++Hello World – C++

#include <iostream>#include <iostream>#include <string>#include <string>using namespaceusing namespace std;std;

intint main() main(){{

// create string ‘str’ = “Hello world!”// create string ‘str’ = “Hello world!”string str = string str = “Hello World!”;“Hello World!”;

cout << str << endl;cout << str << endl;returnreturn 0; 0;

}}

Page 8: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

StringString

To use the To use the stringstring type simply type simply include its header file.include its header file.#include <string>#include <string>

Page 9: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

CreatingCreating stringsstrings

string str = “some text”;string str = “some text”;

oror

string str(“some text”);string str(“some text”);

other ways:other ways:

string s1(7,‘a’);string s1(7,‘a’);

string s2 = s1;string s2 = s1;

Page 10: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

string lengthstring length

The length of string is returned The length of string is returned by itsby its size()size() operationoperation..

#include <string>#include <string>

string str = string str = “something”;“something”;cout << cout << “The size of “ “The size of “

<< str<< str<< << “is ““is “ << str.size() << str.size()<< << “characters.”“characters.” << endl; << endl;

Page 11: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

The size methodThe size method

str.size() ???str.size() ???In In C C we had we had structs containing structs containing only data, only data, In C++, we have :In C++, we have :

class class stringstring {{

…… public:public:

……unsigned intunsigned int size(); size();……

};};

Page 12: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

String concatenationString concatenation

concatenating one string to concatenating one string to another is done by the another is done by the ‘+’ ‘+’ operator.operator.

string str1 = string str1 = “Here ”;“Here ”;string str2 = string str2 = “comes the sun”;“comes the sun”;string concat_str = str1 string concat_str = str1 ++ str2; str2;

Page 13: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

String comparisonString comparison

To check if two strings are equal To check if two strings are equal useusethe the ‘==‘‘==‘ operator. operator.

string str1 = string str1 = “Here ”;“Here ”;string str2 = string str2 = “comes the sun”;“comes the sun”;

if if ( str1 == str2 )( str1 == str2 )/* do something *//* do something */

elseelse/* do something else *//* do something else */

Page 14: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

String assignmentString assignment

To assign one string to another To assign one string to another

use the use the “=““=“ operator. operator.

string str1 = string str1 = “Sgt. Pappers”;“Sgt. Pappers”;

string str2 = string str2 = “lonely hearts club bend”;“lonely hearts club bend”;

str2 str2 == str1; str1;

Now : str2 equals “Now : str2 equals “Sgt. PappersSgt. Pappers””

Page 15: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

What more ?What more ?

Containers Containers AlgorithmsAlgorithms

Page 16: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

ContainersContainers

Data structures that hold Data structures that hold anythinganything (other objects). (other objects).

list: doubly linked list.list: doubly linked list.vector: similar to a C array, but vector: similar to a C array, but dynamic.dynamic.

map: set of ordered key/valuemap: set of ordered key/value pairs. pairs.

Set: set of ordered keys.Set: set of ordered keys.

Page 17: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

AlgorithmsAlgorithms

genericgeneric functions that handle functions that handle common taskscommon taskssuch as searching, sorting, such as searching, sorting, comparing, comparing, and editing:and editing:

findfindmergemergereversereversesortsortand more: count, random shuffle, and more: count, random shuffle, remove, Nth-element, rotate.remove, Nth-element, rotate.

Page 18: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

VectorVector

Provides an alternative to the Provides an alternative to the built in array.built in array.

A vector is self grown. A vector is self grown. Use It instead of the built in Use It instead of the built in

array!array!

Page 19: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Defining a new vectorDefining a new vector

SyntaxSyntax: : vector<vector<of whatof what>>

For example :For example :vector<vector<intint> - > - vector of integers.vector of integers.vector<vector<stringstring> - > - vector of strings.vector of strings.vector<vector<int *int * > - > - vector of pointers vector of pointers to to integers.integers.vector<vector<ShapeShape> - > - vector of Shape vector of Shape objects. Shape is a user defined objects. Shape is a user defined class.class.

Page 20: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Using VectorUsing Vector

##include <vector>include <vector>

Two ways to use the vector Two ways to use the vector type:type:

1.1. Array style.Array style.

2.2. STL styleSTL style

Page 21: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Using a Vector – Array Using a Vector – Array StyleStyle

We mimic the use of built-in array.We mimic the use of built-in array.

voidvoid simple_example() simple_example(){{

const intconst int N = 10; N = 10;vector<vector<intint> ivec(N);> ivec(N);

forfor ( (intint i=0; i < 10; ++i) i=0; i < 10; ++i)

cin >> ivec[i];cin >> ivec[i];

intint ia[N]; ia[N];forfor ( ( intint j = 0; j < N; ++j) j = 0; j < N; ++j)

ia[j] = ivec[j];ia[j] = ivec[j];}}

Page 22: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Using a vector – STL Using a vector – STL stylestyle

We define an empty vectorWe define an empty vectorvector<vector<stringstring> svec;> svec;

we insert elements into the we insert elements into the vector using the method vector using the method push_back.push_back.

stringstring word; word;whilewhile ( cin >> word ) ( cin >> word ) //the number of //the number of

words is unlimited.words is unlimited.

{{svec.push_back(word);svec.push_back(word);

}}

Page 23: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

InsertionInsertion

void void push_backpush_back(const T& x); (const T& x);

Inserts an element with value Inserts an element with value x at the end of the controlled x at the end of the controlled sequence.sequence.

svec.push_back(str);svec.push_back(str);

Page 24: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

SizeSize

unsigned intunsigned int sizesize(); ();

Returns the length of the Returns the length of the controlled sequence (how many controlled sequence (how many items it contains).items it contains).

unsigned intunsigned int size = svec.size(); size = svec.size();

Page 25: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Class Exercise 1Class Exercise 1

Write a program that read Write a program that read integers from the user, sorts integers from the user, sorts them, and print the result.them, and print the result.

Page 26: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Solving the problemSolving the problem

Easy way to read input.Easy way to read input. A “place” to store the inputA “place” to store the input A way to sort the stored input.A way to sort the stored input.

Page 27: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Using STLUsing STL

intint main() main(){{

intint input; input;vector<vector<intint> ivec;> ivec;

/* rest of code *//* rest of code */}}

Page 28: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

STL - InputSTL - Input

whilewhile ( cin >> input ) ( cin >> input )ivec.push_back(input);ivec.push_back(input);

Page 29: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

STL - SortingSTL - Sorting

sortsort(ivec.begin(), ivec.end());(ivec.begin(), ivec.end());

Sort Prototype:Sort Prototype:void sortvoid sort(Iterator first, Iterator (Iterator first, Iterator last); last);

Page 30: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

STL - OutputSTL - Output

forfor ( ( intint i = 0; i < ivec.size(); ++i ) i = 0; i < ivec.size(); ++i )cout << ivec[i] << " ";cout << ivec[i] << " ";

cout << endl;cout << endl;

vector<vector<intint>::iterator it;>::iterator it;forfor ( it = ivec.begin(); it != ivec.end(); ++it ) ( it = ivec.begin(); it != ivec.end(); ++it )

cout << *it << " ";cout << *it << " ";cout << endl;cout << endl;

Or (more recommended)Or (more recommended)

Page 31: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

STL - Include filesSTL - Include files

#include <iostream>#include <iostream> // I/O// I/O#include <vector>#include <vector> // container// container#include <algorithm>#include <algorithm> // sorting// sorting //using namespace std;//using namespace std;

Page 32: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Putting it all togetherPutting it all togetherintint main() { main() {

intint input; input;vector<vector<intint> ivec;> ivec;

// input// inputwhilewhile (cin >> input ) (cin >> input )

ivec.push_back(input);ivec.push_back(input);

// sorting// sortingsort(ivec.begin(), ivec.end());sort(ivec.begin(), ivec.end());

// output// outputvector<vector<intint>::iterator it;>::iterator it;forfor ( it = ivec.begin(); ( it = ivec.begin(); it != ivec.end(); ++it ) { it != ivec.end(); ++it ) {

cout << *it << " ";cout << *it << " ";}}cout << endl;cout << endl;

returnreturn 0; 0;}}

Page 33: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Operations on vectorOperations on vector

iterator iterator beginbegin();(); iterator iterator endend(); (); bool bool emptyempty(); (); void void push_backpush_back(const T& x); (const T& x); iterator iterator eraseerase(iterator it); (iterator it); iterator iterator eraseerase(iterator first, iterator last); (iterator first, iterator last); void void clearclear(); (); ……..

Page 34: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a
Page 35: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Standard C++ LibraryStandard C++ Library

Part IIPart II

Page 36: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Last TimeLast Time

String abstractionString abstraction Containers - vectorContainers - vector

Page 37: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

TodayToday

MapMap pair pair copy algorithmcopy algorithm

Page 38: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

EmployeeEmployee

classclass Employee { Employee {public:public:

// Constructors ...:// Constructors ...: Employee () {}Employee () {} Employee (Employee (const string&const string& name) : _name(name) {} name) : _name(name) {}

// Member functions ...:// Member functions ...: voidvoid set_salary(int salary) {_salary = salary; }set_salary(int salary) {_salary = salary; } intint salary() salary() constconst { { returnreturn _salary; } _salary; } voidvoid set_name( set_name(const string&const string& name) { _name = name; } name) { _name = name; } constconst string&string& name() name() constconst { { returnreturn _name;} _name;}

// …// …private:private:

intint _salary; _salary; stringstring _name; _name;

};};

Page 39: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Locating an EmployeeLocating an Employee

Save all employees in a vector.Save all employees in a vector.

When we need to find a specific When we need to find a specific employee:employee:

go over all employees until go over all employees until you you find one that its name find one that its name matches matches the requested name. the requested name.

Bad solution - not efficient!Bad solution - not efficient!

Page 40: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Solution:Solution:Map – Associative ArrayMap – Associative Array

Most useful when we want to Most useful when we want to store (and possibly modify) an store (and possibly modify) an associated value.associated value.

We provide a We provide a key/value pairkey/value pair. The . The key serves as an key serves as an indexindex into the into the map, the value serves as the map, the value serves as the datadata to be stored. to be stored.

Insertion/find operation - Insertion/find operation - O(logn)O(logn)

Page 41: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Using MapUsing Map

Have a map, where the key will Have a map, where the key will be the employee name and the be the employee name and the value – the employee object.value – the employee object.

name name employee.employee.

stringstring classclass Employee Employee

mapmap<<stringstring, Employee *> employees;, Employee *> employees;

Page 42: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Populating a MapPopulating a Map

void void main()main(){{ mapmap<<stringstring, Employee *> employees;, Employee *> employees; stringstring name( name(“Eti”“Eti”);); Employee *employee; Employee *employee;

employee = employee = newnew Employee(name); Employee(name);

//insetrion//insetrion employees[name] = employee; employees[name] = employee; }}

Page 43: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Locating an EmployeeLocating an Employee

mapmap<<stringstring, Employee> employees;, Employee> employees;

Looking for an employee named Eti :Looking for an employee named Eti :

//find//findEmployee *eti = employees[Employee *eti = employees[“Eti”“Eti”];];//or//ormapmap<<stringstring, Employee *>::, Employee *>::iteratoriterator iter = iter = employees.employees.findfind((“Eti”“Eti”););

The returned value is an The returned value is an iteratoriterator to map. to map. If If “Eti” “Eti” exists on map,exists on map, it points to this value, it points to this value, otherwise, it returns the end() iterator of map. otherwise, it returns the end() iterator of map.

Page 44: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Iterating Across a MapIterating Across a Map

Printing all map contents. Printing all map contents.

mapmap<<stringstring,Employee *>::,Employee *>::iteratoriterator it; it;forfor ( it = employees.begin(); ( it = employees.begin();

it != employees.end(); ++it ) it != employees.end(); ++it ){{

cout << ???cout << ???}}

Page 45: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

IteratorsIterators

Provide a Provide a general way for general way for accessingaccessing each element in each element in sequential (vector, list) or sequential (vector, list) or associative (map, set) associative (map, set) containers.containers.

Page 46: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Pointer SemanticsPointer Semantics

LetLet iteriter be an iterator then :be an iterator then :• ++iter++iter (or (or iter++iter++) )

Advances the iterator to the next Advances the iterator to the next elementelement

• *iter*iter Returns the value of the Returns the value of the element addressed by the element addressed by the iterator.iterator.

Page 47: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Begin and EndBegin and End

Each container provide a Each container provide a begin()begin() and and end()end() member functions. member functions.• begin()begin() Returns an iterator that Returns an iterator that addresses the addresses the firstfirst element of element of the container.the container.• end()end() returns an iterator thatreturns an iterator that addresses addresses 1 past the last1 past the last element.element.

Page 48: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Iterating Over Iterating Over ContainersContainers

Iterating over the elements of any Iterating over the elements of any container type.container type.

forfor ( iter = container.begin(); ( iter = container.begin(); iter != container.end(); iter != container.end(); ++iter ) ++iter ){{

// do something with the element// do something with the element}}

Page 49: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Map IteratorsMap Iterators

mapmap<key, value>::<key, value>::iteratoriterator iter; iter;

What type of element iter does What type of element iter does addresses?addresses?The key ?The key ?

The value ?The value ?

It addresses a It addresses a key/value pairkey/value pair..

Page 50: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

PairPair

Stores a pair of objects, first Stores a pair of objects, first of type of type TT11, and second of type , and second of type TT22..

structstruct pairpair<T1, T2><T1, T2>{{

T1 first;T1 first;T2 second;T2 second;

};};

Page 51: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Our PairOur Pair

In our example iter addresses aIn our example iter addresses apair<pair<stringstring, Employee *>, Employee *>

Element.Element.

Accessing the name (key)Accessing the name (key)iter->firstiter->first

Accessing the Employee* (value)Accessing the Employee* (value)iter->seconditer->second

Page 52: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Printing the SalaryPrinting the Salary

forfor ( iter = employees.begin(); ( iter = employees.begin(); iter != employees.end(); iter != employees.end(); ++iter ) ++iter ){{

cout << iter->first << “ “ cout << iter->first << “ “ << (iter->second)->salary(); << (iter->second)->salary();

}}

Page 53: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Example OutputExample Output

alon 3300alon 3300

dafna 10000dafna 10000

eyal 5000eyal 5000

nurit 6750nurit 6750

Page 54: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Map Sorting SchemeMap Sorting Scheme

map holds its content sorted by map holds its content sorted by key.key.

We would like to sort the map We would like to sort the map using another sorting scheme. using another sorting scheme. (by salary)(by salary)

Page 55: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Map Sorting ProblemMap Sorting Problem

ProblemProblem::

Since map already holds the Since map already holds the elements sorted, we can’t sort elements sorted, we can’t sort them. them.

SolutionSolution::

Copy the elements to a Copy the elements to a container where we can control container where we can control the sorting scheme.the sorting scheme.

Page 56: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

CopyCopy

copycopy((IteratorIterator first, first, IteratorIterator last, last, IteratorIterator where); where);

Copy from ‘first’ to ‘last’ into Copy from ‘first’ to ‘last’ into ‘where’.‘where’.

intint ia[] = { 0, 1, 1, 2, 3, 5, 5, 8 }; ia[] = { 0, 1, 1, 2, 3, 5, 5, 8 }; vectorvector<<intint> ivec1(ia, ia + 8 ), ivec2;> ivec1(ia, ia + 8 ), ivec2; // ...// ... copycopy(ivec1.begin(),ivec1.end(),(ivec1.begin(),ivec1.end(),

ivec2.begin() );ivec2.begin() );

Page 57: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

The ProblemThe Problem

ivec2ivec2 has been allocated no has been allocated no space.space.

The The copycopy algorithm uses algorithm uses assignment to copy each assignment to copy each element value.element value.

copycopy will fail, because there is will fail, because there is no space available.no space available.

Page 58: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

The Solution: use The Solution: use back_inserter()back_inserter()

Causes the container’sCauses the container’s push_backpush_back operation to be invoked.operation to be invoked.

The argument to The argument to back_inserter back_inserter is is the container itself.the container itself.

// // ok. copy now inserts using ok. copy now inserts using ivec2.push_back()ivec2.push_back()copycopy(ivec1.begin(),ivec1.end(), (ivec1.begin(),ivec1.end(),

back_inserterback_inserter(ivec2) );(ivec2) );

Page 59: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Inserter iterators.Inserter iterators.

Puts an algorithm into an Puts an algorithm into an “insert mode”“insert mode” rather than rather than “over write mode”.“over write mode”.

iter =iter = causes an causes an insertioninsertion at at that position, (instead of that position, (instead of overwriting).overwriting).

Page 60: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Employee copyEmployee copy

mapmap<<stringstring, Employee *> employees;, Employee *> employees;vectorvector< < pairpair<<stringstring, Employee *> > evec;, Employee *> > evec;

copycopy( employees.begin(), employees.end(),( employees.begin(), employees.end(), back_inserter( evec ) ); back_inserter( evec ) );

Now it works!!!Now it works!!!

Page 61: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

SortSort

Formal definition :Formal definition :

voidvoid sortsort((IteratorIterator first, first, IteratorIterator last); last);

Page 62: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

SortSort

sort( Iterator begin, Iterator end );sort( Iterator begin, Iterator end );

Example:Example:vectorvector<<intint> ivec;> ivec;

// Fill ivec with integers …// Fill ivec with integers …

sort(ivec.begin(), ivec.end())sort(ivec.begin(), ivec.end())

Page 63: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Inside SortInside Sort

Sort uses operator Sort uses operator to sort to sort two elements.two elements.

What happens when sorting is What happens when sorting is meaningful, but no operator meaningful, but no operator is defined ? is defined ?

Page 64: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

The meaning of The meaning of operator operator

What does it mean to write :What does it mean to write :

pairpair<<stringstring, Employee *> p1, p2;, Employee *> p1, p2;if ( p1 < p2 ) {if ( p1 < p2 ) { … …}}

Page 65: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

The meaning of The meaning of operator operator

No operator No operator is defined is defined between two pairs.between two pairs.

How can we sort a vector of How can we sort a vector of pairs ?pairs ?

Page 66: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Sorting FunctionSorting Function

Define a function that knows Define a function that knows how to sort these elements, and how to sort these elements, and make the sort algorithm use it.make the sort algorithm use it.

Page 67: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

lessThen FunctionlessThen Function

boolbool

lessThen(lessThen(pairpair<<stringstring, Employee *> &l,, Employee *> &l, pairpair<<stringstring, Employee *> &r ) , Employee *> &r )

{{returnreturn (l.second)->Salary() < (l.second)->Salary() < (r.second)->Salary() (r.second)->Salary()

}}

Page 68: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Using lessThenUsing lessThen

vectorvector< < pairpair<<stringstring, Employee *> > evec;, Employee *> > evec;

// Use lessThen to sort the vector.// Use lessThen to sort the vector.sortsort(evec.begin(), evec.end(), lessThen);(evec.begin(), evec.end(), lessThen);

pointer to functionpointer to function

Page 69: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Sorted by SalarySorted by Salary

alon 3300alon 3300

eyal 5000eyal 5000

nurit 6750nurit 6750

dafna 10000dafna 10000

Page 70: An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a

Putting it all TogetherPutting it all Together

boolbool lessThen( lessThen( pairpair<…> &p1, pair<…> &p2 ) { … }<…> &p1, pair<…> &p2 ) { … }

intint main() { main() { mapmap<<stringstring, Employee *> employees;, Employee *> employees;

/* Populate the map. */ /* Populate the map. */ vectorvector< < pairpair<string, Employee *> > employeeVec;<string, Employee *> > employeeVec; copycopy( employees.begin(), employees.end(),( employees.begin(), employees.end(), back_inserterback_inserter( employeeVec ) );( employeeVec ) );

sortsort( employeeVec.begin(), employeeVec.end(),( employeeVec.begin(), employeeVec.end(), lessThen ); lessThen );

vectorvector< < pairpair<<stringstring, Employee *> >::, Employee *> >::iteratoriterator it; it; forfor ( it = …; it != employeeVec.end(); ++it ) { ( it = …; it != employeeVec.end(); ++it ) { cout << (it->second)->getName() << " " cout << (it->second)->getName() << " " << (it->second)->getSalary() << endl; << (it->second)->getSalary() << endl; } } returnreturn 0; 0;}}