Standard Template Libraries

Post on 14-Jan-2016

46 views 1 download

Tags:

description

Standard Template Libraries. Anjali Agrawal Prashant Kirtane. Beginning STL !. What ought to be in standard C++ Library ? Everything !!. The C++ Standard Library. Memory management Type safe by default supplies functions such as sqrt() Efficient Complete. Why STL ?. - PowerPoint PPT Presentation

Transcript of Standard Template Libraries

Standard Template Libraries

Anjali Agrawal

Prashant Kirtane

2

Beginning STL !

What ought to be in standard C++ Library ?

Everything !!

3

The C++ Standard Library

Memory management Type safe by default supplies functions such as sqrt() Efficient Complete

4

Why STL ?

Flexibility The use of generic algorithms allows algorithms to be applied to many different structures.

Efficiency STL containers are very close to the efficiency of hand-coded, type-specific containers.

Easy-to-learn structure The library is quite small owing to the high degree of genericity.

5

Brains !

Alex Stepanov and Meng Lee of Hewlett-Packard Labs.

July 1994, the ANSI/ISO C++ Standards Committee voted to adopt STL as part of the standard C++ library.

6

Structure of the library

Contains 5 type of components.– Algorithm– Container– Iterator– Function Object– Adaptor

7

What are Containers ?

A Container is a way that stored data is organized in memory.

Data may be of built-in types or of class objects.

E.g. Arrays, Stacks, Linked lists.

8

Containers !

Objects

Containers

9

Now What ?

Containers

Objects

How do you access this collection of data?

How do you use them?

10

Algorithms

Are stand alone functions that performs operations on collections of data(containers).

Are designed to work on STL containers but we can also apply on C++ arrays.

11

E.g. Algorithms on C++ arrays

#include <algo.h>

……

int iArr[] = {4, 2, 1, 3};

sort(iArr, iArr+4);

Address of the beginning of the array

Past-the-end address

12

The find() Algorithm

Looks for the first element in a container that has a specified value.

….

Int iArr[] = {4, 3, 1, 2};

int *iPtr;

iPtr = find(iArr, iArr+4, 3);Specified value

13

The count() Algorithm

Counts the number of elements in a container having a specified value.

…….

Int iArr[] = {2, 3, 3, 1};

count(iArr, iArr+4, 3, nVar);

Number of counts ….

Keeps on adding.Specified value

14

Algorithms …….

Equal .. Compares the contents of two containers and returns true if all corresponding elements are equal.

Search, copy, swap, sort …..etc

15

Function Objects !

An object of a template class that has a single member function : the overloaded () operator.

Sound mysterious ! But its easy to use.

16

Why do you require Function Objects ? There are some algorithms which take

this function objects as an arguments.

Int iArr[] = {2, 4, 1, 3};

sort(iArr, iArr+4, greater<int>());

greater<>() function object

sorts array in descending order..

17

User written functions ...

User written functions in place of function objects.

Required since function objects operate only on basic C++ types and on classes for which appropriate (+, <) operators are defined.

E.g. ‘<‘ is not defined for char*

18

E.g. User defined functions ..

sort(cpNames, cpNames+4, bAlphaComp);

Address of the bAlphaComp function

Int bAlphaComp(char * s1, char *s2)

{

return(strcmp(……));

}

19

Container Types !

20

Sequence Containers

are objects that store collections of other objects in a strictly linear arrangement.

Stores a set of elements that can be visualized as a line, like houses on a street.

21

Vectors

provides array-like random access to a sequence of varying length, with constant time insertions and deletions at the end.

#include<vector.h>

………

vector<int> aIntVector;

22

Vectors … member functions

Vector<int> aIntVect;

aIntVect.push_back(10);

aIntVect.push_back(11);

for(int j = 0; j < aIntVect.size(), j++)

cout << aIntVect[j];

Returns the no of elements currently in the container

Inserts the value at the back

Overloading [] operator

23

Vectors … member functions

Char *cpChar[] = {“prash”, “is”, “a”, “good”, “boy”};

vector<char *> aCharVect(cpChar, cpChar+5);

vector<char *> aEmpVect(5);

aCharVect.swap(aEmpVect);

Initializing the vector

Empty vector of size 5

Swap contents of two vectors

24

Vectors .. Member functions

Int iArr[] = {1, 2, 4, 5};

vector<int> aIntVect(iArr, iArr+4);

aIntVect.insert(aIntVect.begin()+2, 3);

aIntVect.erase(aIntVect.begin()+2);

Inefficient

25

List

Doubly linked list. which provides linear time access to a

sequence of varying length, with constant time insertions and deletions anywhere.

#include <list.h>

……….

List<char> aCharList;

26

List …. Member functions

list<int> aIntList;

aIntList.push_back(2);

aIntList.push_back(3);

aIntList.push_front(1);

aIntList.pop_front();

Push items on back

Push items on front

Pop items off front

27

More on Lists …..

[] operator is not defined for lists.

list<int> list1;

list<int> list2;

…..

list1.reverse();

list1.merge(list2);

28

Deque

Double- ended queue. which provides random access to a

sequence of varying length, with constant time insertions and deletions at both ends

Similar to vector, but can be accessed at either end.

29

Deques….

#include <deque.h>

….

deque<int> aDeque;

aDeque.push_back(1);

aDeque.push_back(2);

aDeque.push_front(3);

30

Till Now … Lets Revise !!!

Containers.– Sequential Containers

• Vectors• Lists• Deques

Algorithms

31

Common Questions ….

What is the difference between Vectors and Deques ?

When to use .. What ?

32

Iterators

Pointer-like entities used to access individual data items in a container.

Used to move sequentially from element to element called iterating through the container.

33

Algorithms use the iterators to act on objects in containers ....

Algorithm

Algorithm

Iterators Containers

34

Types of Iterators !

Input iterator. Output iterator. Forward iterator. Bidirectional iterator. Random-access iterator.

35

Iterators as an interface

Decides which algorithm can be used with which container.

E.g. To be efficient, the reverse() algorithm needs to iterate backward as well as forward through a container.

36

Using Iterators !

list <int> iList;

list<int> :: iterator it;List of ints

Iterator to the list-of-ints

37

More on Iterators…..

int iArr[] = {1, 2, 3, 4};

list<int> iList(iArr, iArr+4);

list<int> :: iterator it;

for(it = iList.begin(); it != iList.end(); it++)

cout << *it << endl; Iterator required since “list” doesn’t

support random access.

38

Algorithms and Iterators !

Algorithms can take iterators as its arguments.

list<int> iList;

list<int> :: iterator it;

it = find(iList.begin(), iList.end(), 8);

39

Specialized Iterators !

Iterator Adapters– Reverse Iterators– Insert iterators– Raw storage iterators

Stream Iterators– Input stream iterators– Output stream iterators

40

Reverse Iterators !

Allows to move backwards in the container.

List<int> iList(iArr, iArr+4);

list<int> :: reverse_iterator rit;

rit = iList.rbegin();

while(rit != iList.rend())

cout << *rit++ << endl;

41

Insert Iterators !

Allows the data to be inserted without overwriting the existing data.

back_inserter .. Inserts new items at the end.

front_inserter .. Inserts new items at the beginning.

inserter .. Inserts new items at a specified location.

42

E.g. Insert Iterator

copy(d1.begin(), d1.end(), back_inserter(d2));

copy(d1.begin(), d1.end(), front_inserter(d2));

copy(d1.begin(), d1.end(), inserter(d2, d2.begin() ) );

43

Stream Iterators

Allows to treat I/O devices and files as iterators.

Files and I/O devices as arguments to algorithms.

ostream_iterator istream_iterator

Stream Iterators

44

The ostream_iterator Class !

An ostream_iterator object can be used as an argument to any algorithm that specifies an output iterator.

ostream_iterator<int> ositer(cout, “--”);

……

copy(iList.begin(), iList.end(), oister);

Stream to write

45

ostream_iterator … to a file !

ofstream outfile(“iter.data”);

ostream_iterator<int> ositer(outfile, “ “);

copy(iList.begin(), iList.end(), ositer);

Create file object

Defining Iterator ….

Write List to file

46

The istream_iterator class

An istream_iterator object can be used as an argument to any algorithm that specifies an input iterator.

istream_iterator<float, ptrdiff_t> cit(cin);

istream_iterator<float, ptrdiff_t> end_of_stream; ……..

copy(cit, end_of_stream, fList.begin());

47

istream_iterator …from a file !

ifstream infile(“iter.dat”);

istream_iterator<int, ptrdiff_t> file_iter(infile);

istream_iteratot<int, ptrdiff_t> end_of_stream;

copy(file_iter, end_of_stream, back_inserter(iList));

48

Associative Containers

provide for fast retrieval of objects from the collection based on keys.

Is not sequential, instead it uses keys to access data.

Sets and Maps.

49

Map

supports unique keys (contains at most one of each key value) and provides for fast retrieval of another type T based on the keys.

The keys are arranged in sorted order.

50

A map of number-word pairs

Cat1

Dog

Snail

2

3

2 Values

Keys

51

More on Maps…...

typedef map<int, char*, less<int> > map_type;

map_type aMap;

map_type :: iterator it;

aMap.insert(map_type::value_type(1, “Cat”) );

aMap.insert(map_type::value_type(2, “Dog”) );

it = aMap.begin();

52

Multimap

which supports duplicate keys (possibly contains multiple copies of the same key value) and provides for fast retrieval of another type T based on the keys.

53

Set

which supports unique keys (contains at most one of each key value) and provides for fast retrieval of the keys themselves

Similar to map but it stores only keys, there are no values.

54

A Set of Characters …..

c

d

f

fKeys

55

Sets ….

set<int, less<int> > aIntSet(iArr, iArr+4);

set<int, less<int> > :: iterator it;

it = aIntSet.begin();

while(it != aIntSet.end())

cout << *it++ << endl;

Definition for sets ….

Iterator for sets ...

56

More on Sets…..

aIntSet.insert(3);

aIntSet.insert(4);

aIntSet.insert(3);

aIntSet.erase(4);

it = aIntSet.find(3);

Inserts some more ints

No effect, already inserted

Erase a int

Finding matching int in set

57

Multiset

which supports duplicate keys (possibly contains multiple copies of the same key value) and provides for fast retrieval of the keys themselves.

Same as Set, but multiple instances of the same key.