An Introduction to STL. The C++ Standard Template Libraries In 1990, Alex Stepanov and Meng Lee of...

Preview:

Citation preview

An Introduction to STLAn Introduction to STL

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

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.

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

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

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

}}

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;

}}

StringString

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

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;

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;

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

};};

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;

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 */

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

What more ?What more ?

Containers Containers AlgorithmsAlgorithms

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.

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.

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!

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.

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

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

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

}}

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

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

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.

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.

Using STLUsing STL

intint main() main(){{

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

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

STL - InputSTL - Input

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

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

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)

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;

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

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

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