Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

36
Standard C++ Library Standard C++ Library Part II Part II

Transcript of Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

Page 1: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

Standard C++ LibraryStandard C++ Library

Part IIPart II

Page 2: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

Last TimeLast Time

String abstractionString abstraction Containers - vectorContainers - vector

Page 3: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

TodayToday

MapMap pair pair copy algorithmcopy algorithm

Page 4: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 5: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 6: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 7: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 8: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 9: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 10: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 11: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 12: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 13: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 14: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 15: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 16: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 17: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 18: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 19: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

Example OutputExample Output

alon 3300alon 3300

dafna 10000dafna 10000

eyal 5000eyal 5000

nurit 6750nurit 6750

Page 20: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 21: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 22: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 23: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 24: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 25: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 26: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 27: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

SortSort

Formal definition :Formal definition :

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

Page 28: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 29: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 30: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 31: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 32: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 33: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 34: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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 35: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

Sorted by SalarySorted by Salary

alon 3300alon 3300

eyal 5000eyal 5000

nurit 6750nurit 6750

dafna 10000dafna 10000

Page 36: Standard C++ Library Part II. Last Time b String abstraction b Containers - vector.

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