an introduction to stl. the c++ standard template libraries in 1990, alex stepanov and meng lee of...
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/1.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/2.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/3.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/4.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/5.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/6.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/7.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/8.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/9.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/10.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/11.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/12.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/13.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/14.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/15.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/16.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/17.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/18.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/19.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/20.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/21.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/22.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/23.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/24.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/25.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/26.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/27.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/28.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/29.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/30.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/31.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/32.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/33.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/34.jpg)
![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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/35.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/36.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/37.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/38.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/39.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/40.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/41.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/42.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/43.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/44.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/45.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/46.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/47.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/48.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/49.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/50.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/51.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/52.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/53.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/54.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/55.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/56.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/57.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/58.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/59.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/60.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/61.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/62.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/63.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/64.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/65.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/66.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/67.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/68.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/69.jpg)
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](https://reader030.vdocuments.net/reader030/viewer/2022033021/56649f2a5503460f94c44176/html5/thumbnails/70.jpg)
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;}}