Post on 18-Jan-2016
Standard C++ LibraryStandard C++ Library
Part IIPart II
Last TimeLast Time
String abstractionString abstraction Containers - vectorContainers - vector
TodayToday
MapMap pair pair copy algorithmcopy algorithm
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;
};};
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!
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)
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;
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; }}
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.
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 << ???}}
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.
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.
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.
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}}
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..
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;
};};
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
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();
}}
Example OutputExample Output
alon 3300alon 3300
dafna 10000dafna 10000
eyal 5000eyal 5000
nurit 6750nurit 6750
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)
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.
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() );
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.
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) );
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).
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!!!
SortSort
Formal definition :Formal definition :
voidvoid sortsort((IteratorIterator first, first, IteratorIterator last); last);
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())
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 ?
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 ) { … …}}
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 ?
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.
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()
}}
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
Sorted by SalarySorted by Salary
alon 3300alon 3300
eyal 5000eyal 5000
nurit 6750nurit 6750
dafna 10000dafna 10000
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;}}