Standard Template Library

90
Standard Standard Template Library Template Library C++ Library of templates C++ Library of templates Unit - 11 Unit - 11

description

Unit - 11. Standard Template Library. C++ Library of templates. Unit Introduction. This unit covers standard template library. Unit Objectives. After covering this unit you will understand… Standard template library String library IOStream library General template library - PowerPoint PPT Presentation

Transcript of Standard Template Library

Page 1: Standard Template Library

Standard Standard Template LibraryTemplate Library

C++ Library of templatesC++ Library of templates

Unit - 11Unit - 11

Page 2: Standard Template Library

2

Unit IntroductionUnit Introduction

This unit covers standard template This unit covers standard template librarylibrary

Page 3: Standard Template Library

3

Unit ObjectivesUnit Objectives

After covering this unit you will After covering this unit you will understand…understand…

Standard template libraryStandard template library String libraryString library IOStream libraryIOStream library General template libraryGeneral template library STL containers and iteratorsSTL containers and iterators STL algorithmsSTL algorithms

Page 4: Standard Template Library

4

IntroductionIntroduction

STL stands for ‘Standard Template STL stands for ‘Standard Template Library’ Library’

Complements the C++ librariesComplements the C++ libraries STL provides certain features, which STL provides certain features, which

include:include: String libraryString library Input/Output stream libraryInput/Output stream library Localization libraryLocalization library Containers libraryContainers library

Page 5: Standard Template Library

5

Introduction (contd.)Introduction (contd.) Iterators libraryIterators library Algorithms libraryAlgorithms library Numerics libraryNumerics library Diagnostics libraryDiagnostics library Language Support libraryLanguage Support library General Utilities libraryGeneral Utilities library

The purpose of STL is to provide The purpose of STL is to provide standardised set of toolsstandardised set of tools

These tools become the building These tools become the building blocks of most programsblocks of most programs

Page 6: Standard Template Library

6

Strings LibraryStrings Library

It provides a set of functions to It provides a set of functions to implement the low-level implement the low-level manipulation featuresmanipulation features

A string is a character array with a A string is a character array with a null terminator (binary zero)null terminator (binary zero)

STL uses string object for string STL uses string object for string manipulationmanipulation

Page 7: Standard Template Library

7

Characteristics of String Characteristics of String ObjectObject

A string object has:A string object has: Starting location in memoryStarting location in memory contentscontents LengthLength no NULL terminatorno NULL terminator

A string automatically resizes A string automatically resizes according to length of its contentsaccording to length of its contents

In case of reference counting, In case of reference counting, stringstring may occupy specific physical memorymay occupy specific physical memory

Page 8: Standard Template Library

8

Advantages of String Advantages of String ObjectObject

It has the following three It has the following three advantages over the character array, advantages over the character array, used in C++:used in C++: Checks overwriting array boundsChecks overwriting array bounds Checks for uninitialized pointers before Checks for uninitialized pointers before

using stringsusing strings Releases memory storage for dangling Releases memory storage for dangling

pointerspointers

Page 9: Standard Template Library

9

Creating StringsCreating Strings

Create an empty Create an empty string string and defer and defer initializing it with character datainitializing it with character data

Initialize a Initialize a string string by passing a literal, by passing a literal, quoted character array as an quoted character array as an argument to the constructorargument to the constructor

Initialize a Initialize a string string using using ‘‘==‘‘ Use one Use one string string to initialize anotherto initialize another Use a portion of either a C Use a portion of either a C char char array array

or a C++ or a C++ stringstring

Page 10: Standard Template Library

10

Creating Strings (contd.)Creating Strings (contd.)

Combine different sources of Combine different sources of initialization data using initialization data using operator+operator+

Use the Use the string string object’s object’s substr( ) substr( ) member function to create a member function to create a substringsubstring

Page 11: Standard Template Library

11

Example: Creating Example: Creating StringsStrings

#include <string.h>#include <string.h>

#include <iostream.h>#include <iostream.h>

void main() void main()

{{

string s1 (”This is String 1");string s1 (”This is String 1");

string s2 = “This is String 2”;string s2 = “This is String 2”;

// Copy the first 8 chars// Copy the first 8 chars

string s3(s1, 0, 8);string s3(s1, 0, 8);

// Copy 3 chars from the 5th character of the source// Copy 3 chars from the 5th character of the source

string s4(s2, 5, 3);string s4(s2, 5, 3);

// Copy all sorts of stuff// Copy all sorts of stuff

string mixedStuff = s4 + “hmmm” + s1.substr(10, 5);string mixedStuff = s4 + “hmmm” + s1.substr(10, 5);

// substr() copies 5 chars at element 10// substr() copies 5 chars at element 10

cout << mixedStuff << endl;cout << mixedStuff << endl;

} }

Page 12: Standard Template Library

12

Operating on StringsOperating on Strings

You can perform four basic You can perform four basic operations on a string:operations on a string: AppendAppend InsertInsert ConcatenateConcatenate ReplaceReplace

Page 13: Standard Template Library

13

Example: Operating on Example: Operating on StringsStrings

#include <string.h>#include <string.h>

#include <iostream.h>#include <iostream.h>

void main() void main()

{{

string s1(”This is String 1.");string s1(”This is String 1.");

// How much data have we actually got?// How much data have we actually got?

cout << "Size = " << s1.size() << endl;cout << "Size = " << s1.size() << endl;

// How much can we store without reallocating// How much can we store without reallocating

cout << "Capacity = ” << s1.capacity() << endl;cout << "Capacity = ” << s1.capacity() << endl;

s1.insert(1, "This is Inserted at index 1.");s1.insert(1, "This is Inserted at index 1.");

// Make sure that there will be this much space// Make sure that there will be this much space

s1.reserve(50);s1.reserve(50);

// Add this to the end of the string// Add this to the end of the string

s1.append("I've been working too hard.");s1.append("I've been working too hard.");

string tag(“String”); string tag(“String”); // tag to find// tag to find

int start = s1.find (tag);int start = s1.find (tag); // get the start index// get the start index

s1.replace (start, tag.size(), “hey there”);s1.replace (start, tag.size(), “hey there”);

}}

Page 14: Standard Template Library

14

Searching in StringSearching in String

Following are useful functions used Following are useful functions used for string searching:for string searching: find();find(); find_first_of();find_first_of(); find_last_of();find_last_of(); find_first_not_of();find_first_not_of(); find_last_not_of();find_last_not_of(); rfind();rfind();

Page 15: Standard Template Library

15

Example: Searching in Example: Searching in StringsStrings

#include <string>#include <string>

#include <iostream>#include <iostream>

void main() void main()

{{

string s1(”This is String 1.");string s1(”This is String 1.");

// find the tag// find the tag

string tag(“String”);string tag(“String”);

// get the start index// get the start index

int start = s1.find (tag);int start = s1.find (tag);

// replace the // replace the tag tag totally with the new stringtotally with the new string

s1.replace (start, tag.size(), “hey there”);s1.replace (start, tag.size(), “hey there”);

// finds the ‘i’ in String in s1// finds the ‘i’ in String in s1

int current = s1.rfind(“i”); int current = s1.rfind(“i”);

// finds the first space after ‘This’ in s1// finds the first space after ‘This’ in s1

int space = s1.find_first_not_of(“ “);int space = s1.find_first_not_of(“ “);

}}

Page 16: Standard Template Library

16

String ComparisonString Comparison

Compares the ASCII values of the string Compares the ASCII values of the string characterscharacters Returns 0 if both strings matchReturns 0 if both strings match Returns 1 if string1 has greater ASCII valueReturns 1 if string1 has greater ASCII value Returns -1 if string2 has greater ASCII Returns -1 if string2 has greater ASCII

valuevalue Two types of syntax:Two types of syntax:

string1.compare(string2);string1.compare(string2); strcmp(string1, string2);strcmp(string1, string2);

Page 17: Standard Template Library

17

Example: String Example: String ComparisonComparison

#include <iostream.h>#include <iostream.h>

#include <string.h>#include <string.h>

void main() void main()

{{

string s1(“This is One String”);string s1(“This is One String”);

string s2(“This is the Other String”);string s2(“This is the Other String”);

int result = strcmp(s1, s2); int result = strcmp(s1, s2);

int caseInsensitive = strcmpi(s1, s2);int caseInsensitive = strcmpi(s1, s2);

int result2 = s1.compare(s2);int result2 = s1.compare(s2);

switch (result) switch (result)

{{

case 0: case 0:

cout<<“Both the Strings are equal”;cout<<“Both the Strings are equal”;

break;break;

Page 18: Standard Template Library

18

Example: String Comparison Example: String Comparison (contd.)(contd.)

case -1: case -1:

cout<<“String1 is lexically less than String2”; cout<<“String1 is lexically less than String2”; break; break;

case 1: case 1:

cout<<“String1 is lexically greater than String2”; cout<<“String1 is lexically greater than String2”; break; break;

} } // end switch statement// end switch statement

} } // end main// end main

Page 19: Standard Template Library

19

IOStream LibraryIOStream Library

Deals with the following I/O Deals with the following I/O functions in a safe, efficient and functions in a safe, efficient and easier manner:easier manner: Standard InputStandard Input Standard OutputStandard Output FilesFiles Memory BlocksMemory Blocks

Page 20: Standard Template Library

20

General Template General Template LibraryLibrary

Templates provide an interface to Templates provide an interface to assign variable type or class type, to assign variable type or class type, to be used at runtimebe used at runtime

There are two types of Template There are two types of Template arguments:arguments: Non-type template argumentsNon-type template arguments Default template argumentsDefault template arguments

Page 21: Standard Template Library

21

Example: Non-type Template Example: Non-type Template ArgumentsArguments

#include <string.h>#include <string.h>

#include <sstream.h>#include <sstream.h>

template<typename T>template<typename T>

std::string toString(const T& templateVar) std::string toString(const T& templateVar)

{{

std::ostringstream output;std::ostringstream output;

output << templateVar;output << templateVar;

return output.str();return output.str();

}}

void main() void main()

{{

int i = 1234;int i = 1234;

cout << "i == \"" << toString(i) << "\"\n";cout << "i == \"" << toString(i) << "\"\n";

float x = 567.89;float x = 567.89;

cout << "x == \"" << toString(x) << "\"\n";cout << "x == \"" << toString(x) << "\"\n";

}}

Page 22: Standard Template Library

22

Example: Default Template Example: Default Template ArgumentsArguments

// Using 'typename' to say it's a type,// Using 'typename' to say it's a type,

// and not something other than a type// and not something other than a type

template<class T> template<class T>

class TemplateClass class TemplateClass

{{

// without typename, it is an error// without typename, it is an error

typename T AnyVarType;typename T AnyVarType;

public:public:

void TemplateFunc()void TemplateFunc()

{ {

AnyVarType.Function(); AnyVarType.Function();

}}

};};

class NormalClass class NormalClass

{{

public:public:

void Function() {}void Function() {}

};};

Page 23: Standard Template Library

23

Example: Default Template Arguments Example: Default Template Arguments (contd.)(contd.)

void main()void main()

{{

NormalClass normalObj;NormalClass normalObj;

TemplateClass<NormalClass> templateObj;TemplateClass<NormalClass> templateObj;

templateObj.TemplateFunc();templateObj.TemplateFunc();

}}

Page 24: Standard Template Library

24

Typedef a typenameTypedef a typename

It is recommended to use It is recommended to use typedeftypedef when using when using typenametypename

/* The following causes a variable to be declared of type /* The following causes a variable to be declared of type Seq::iterator */Seq::iterator */

// instead of using// instead of using typename onlytypename only

typename Seq::iterator ItType;typename Seq::iterator ItType;

// use typedef// use typedef

typedef typename Seq::iterator SeqIteratorType;typedef typename Seq::iterator SeqIteratorType;

// now SeqIteratorType is a type and can be used as// now SeqIteratorType is a type and can be used as

SeqIteratorType it;SeqIteratorType it;

Page 25: Standard Template Library

25

Example: Using typename Instead of Example: Using typename Instead of ClassClass

// Using 'typename' in the template argument list// Using 'typename' in the template argument list

template<typename T> template<typename T>

class TemplateClass { };class TemplateClass { };

int main() int main()

{{

TemplateClass<int> templateObj;TemplateClass<int> templateObj;

}}

Page 26: Standard Template Library

26

Function TemplatesFunction Templates

You can create Function Templates You can create Function Templates in places, where in places, where you have a number of functions,you have a number of functions, that look identical, that look identical, but have different data typesbut have different data types

Page 27: Standard Template Library

27

STL Containers and STL Containers and IteratorsIterators Container classesContainer classes are the solution to are the solution to

a specific kind of code reuse problem a specific kind of code reuse problem They are building blocks used to They are building blocks used to

create object-oriented programscreate object-oriented programs They make the internals of a program They make the internals of a program

much easier to constructmuch easier to construct They are sometimes referred to as They are sometimes referred to as

Collection ClassesCollection Classes A container class describes an object A container class describes an object

that holds other objectsthat holds other objects

Page 28: Standard Template Library

28

Why Use Containers?Why Use Containers?

Containers solve the problem of Containers solve the problem of creating objects at runtimecreating objects at runtime

You create another type of object, You create another type of object, the new type of object holds other the new type of object holds other objects, or pointers to objectsobjects, or pointers to objects

It will expand itself whenever It will expand itself whenever necessary to accommodate necessary to accommodate everything you place inside it everything you place inside it

Page 29: Standard Template Library

29

Why Use Containers? Why Use Containers? (contd.)(contd.)

You don’t need to know how many objects You don’t need to know how many objects you’re going to hold in a collectionyou’re going to hold in a collection

You just create a collection object and let You just create a collection object and let it take care of the detailsit take care of the details

You can add/delete elements in a You can add/delete elements in a containercontainer

For fetching/comparing/manipulating For fetching/comparing/manipulating objects within a container, you need an objects within a container, you need an iteratoriterator

Page 30: Standard Template Library

30

IteratorsIterators Iterator’s job is to iterate the elements Iterator’s job is to iterate the elements

within a container within a container Present them to the user of the Present them to the user of the

iteratoriterator The container, via the iterator, is The container, via the iterator, is

abstracted to be simply a sequence abstracted to be simply a sequence The iterator allows you to traverse The iterator allows you to traverse

that sequence without worrying about that sequence without worrying about the underlying structure – that is, the underlying structure – that is, whether it’s a vector, a linked list, a whether it’s a vector, a linked list, a stack or something elsestack or something else

Page 31: Standard Template Library

31

Iterators (contd.)Iterators (contd.)

Gives the flexibility to easily change Gives the flexibility to easily change the underlying data structure the underlying data structure without disturbing the codewithout disturbing the code

Page 32: Standard Template Library

32

Example: String Example: String ContainersContainers#include <string.h>#include <string.h>

#include <vector.h>#include <vector.h>

#include <fstream.h>#include <fstream.h>

#include <iostream.h>#include <iostream.h>

#include <iterator.h>#include <iterator.h>

#include <sstream.h>#include <sstream.h>

void main(int argc, char* argv[]) void main(int argc, char* argv[])

{{

ifstream in(argv[1]);ifstream in(argv[1]);

vector<string> stringVector;vector<string> stringVector;

string inputLine;string inputLine;

// Add to strings container// Add to strings container

while(getline(in, inputLine))while(getline(in, inputLine))

stringVector.push_back(inputLine);stringVector.push_back(inputLine);

int i = 1;int i = 1;

vector<string>::iterator vectorIterator; vector<string>::iterator vectorIterator; // iterator// iterator

Page 33: Standard Template Library

33

Example: String Containers Example: String Containers (contd.)(contd.)

for(vectorIterator = stringVector.begin(); for(vectorIterator = stringVector.begin();

vectorIterator != stringVector.end(); vectorIterator++) vectorIterator != stringVector.end(); vectorIterator++)

{{

ostringstream out;ostringstream out; // define output string stream // define output string stream // object// object

out << i++;out << i++; // outputs the element number// outputs the element number

*vectorIterator = out.str() + ": " + *vectorIterator;*vectorIterator = out.str() + ": " + *vectorIterator;

}}

// write strings to console// write strings to console

// create ostream iterator to write to console// create ostream iterator to write to console

ostream_iterator<string> os_it(cout, "\n");ostream_iterator<string> os_it(cout, "\n");

//copy contents of ‘strings’ to console using the iterator//copy contents of ‘strings’ to console using the iterator

copy(stringVector.begin(), stringVector.end(), os_it);copy(stringVector.begin(), stringVector.end(), os_it);

// string objects clean themselves up when they go out of // string objects clean themselves up when they go out of

// scope// scope

}}

Page 34: Standard Template Library

34

Types of ContainersTypes of Containers

There are two types of containersThere are two types of containers Sequence ContainersSequence Containers: These : These

containers keep the sequence of objects containers keep the sequence of objects in whichever order you want to in whichever order you want to establishestablish

Associative ContainersAssociative Containers: These : These containers keep {key, value} pairs, and containers keep {key, value} pairs, and store/retrieve data using associationsstore/retrieve data using associations

Page 35: Standard Template Library

35

Sequence ContainersSequence Containers

These containers keep the sequence of These containers keep the sequence of objects in whichever order you want to objects in whichever order you want to establishestablish

The different sequence containers are:The different sequence containers are: VectorVector DequeDeque ListList SetSet StackStack QueueQueue

Page 36: Standard Template Library

36

VectorsVectors

It has array-style indexing but also It has array-style indexing but also can expand dynamicallycan expand dynamically

It maintains its storage as a single It maintains its storage as a single contiguous array of objectscontiguous array of objects

It keeps everything in a single It keeps everything in a single sequential block of memory sequential block of memory

Page 37: Standard Template Library

37

Example: VectorsExample: Vectors#include <iostream.h>#include <iostream.h>

#include <vector.h>#include <vector.h>

#include <algorithm.h>#include <algorithm.h>

int Noisy() int Noisy()

{ { // return some random integer// return some random integer

}}

void main() void main()

{{

vector<int> v;vector<int> v;

v.reserve(11);v.reserve(11); // make room for 11 integers// make room for 11 integers

ostream_iterator<int> out(cout, " ");ostream_iterator<int> out(cout, " ");

copy(v.begin(), v.end(), out); copy(v.begin(), v.end(), out); // write to console// write to console

vector<int>::iterator it = v.begin() + v.size() / 2;vector<int>::iterator it = v.begin() + v.size() / 2;

v.insert(it, Noisy()); v.insert(it, Noisy()); // insert an element in middle// insert an element in middle

copy(v.begin(), v.end(), out); copy(v.begin(), v.end(), out); // write to console// write to console

v.erase(it); v.erase(it); // erasing an element from vector// erasing an element from vector

copy(v.begin(), v.end(), out); copy(v.begin(), v.end(), out); // write to console// write to console

}}

Page 38: Standard Template Library

38

DequeDeque

The The deque deque (double-ended-queue, (double-ended-queue, pronounced “deck”) is optimized for pronounced “deck”) is optimized for adding and removing elements from adding and removing elements from either endeither end

Deque Deque uses multiple blocks of uses multiple blocks of sequential storage (keeping track of sequential storage (keeping track of all the blocks and their order in a all the blocks and their order in a mapping structure)mapping structure)

Page 39: Standard Template Library

39

Example: DequeExample: Deque#include <deque.h>#include <deque.h>

#include <iostream.h>#include <iostream.h>

#include <iterator.h>#include <iterator.h>

void main() void main()

{{

deque<int> dequeObj(100, 0);deque<int> dequeObj(100, 0);

ostream_iterator<int> out(cout, " ")ostream_iterator<int> out(cout, " ")

// No problem iterating from beginning to end,// No problem iterating from beginning to end,

// even though it spans multiple blocks// even though it spans multiple blocks

copy(dequeObj.begin(), dequeObj.end(), out);copy(dequeObj.begin(), dequeObj.end(), out);

deque<int>::iterator dequeIterator = dequeObj.begin() + deque<int>::iterator dequeIterator = dequeObj.begin() + dequeObj.size() / 2;dequeObj.size() / 2;

// Walk the iterator forward as you perform// Walk the iterator forward as you perform

// a lot of insertions in the middle// a lot of insertions in the middle

for(int j = 0; j < 1000; j++) for(int j = 0; j < 1000; j++)

{{

cout << j << endl;cout << j << endl;

Page 40: Standard Template Library

40

Example: Deque (contd.)Example: Deque (contd.) dequeObj.insert(dequeIterator++, j); dequeObj.insert(dequeIterator++, j); // Eventually // Eventually

// breaks// breaks

} } //end for loop//end for loop

} } // end main()// end main()

Page 41: Standard Template Library

41

ListList It is implemented as a doubly-linked It is implemented as a doubly-linked

list list It is designed for rapid insertion and It is designed for rapid insertion and

removal of elements in the middle of removal of elements in the middle of the sequencethe sequence

A list is so slow when randomly A list is so slow when randomly accessing elements that it does not accessing elements that it does not have an have an operator[]operator[]

It has a memory overhead of each link, It has a memory overhead of each link, which requires a forward and which requires a forward and backward pointerbackward pointer

Page 42: Standard Template Library

42

Example: ListExample: List#include <list.h>#include <list.h>

#include <iostream.h>#include <iostream.h>

void main() void main()

{{

// create list 100 elements initialized with 0// create list 100 elements initialized with 0

list<int> li(100, 0);list<int> li(100, 0);

// create iterator to traverse the list// create iterator to traverse the list

list<int>::iterator iter = li.begin();list<int>::iterator iter = li.begin();

// insert new elements with value 1// insert new elements with value 1

for(int k = 0; k < 50; k++)for(int k = 0; k < 50; k++)

li.insert(iter++, 1); li.insert(iter++, 1); // No problem// No problem

cout << *iter;cout << *iter; // prints first 0// prints first 0

li.erase(iter); li.erase(iter); // erases first 0// erases first 0

--iter;--iter;

cout << *iter;cout << *iter; // prints the 1// prints the 1

*iter = 2; *iter = 2; // replaces 1 with 2 at the current position// replaces 1 with 2 at the current position

}}

Page 43: Standard Template Library

43

SetSet

It produces a container that will It produces a container that will accept only one of each thing you accept only one of each thing you place in itplace in it

It also sorts the elements in a It also sorts the elements in a balanced binary tree to provide balanced binary tree to provide rapid lookupsrapid lookups

It produces sorted results when you It produces sorted results when you traverse ittraverse it

Page 44: Standard Template Library

44

Example: SetExample: Set#include <string.h>#include <string.h>

#include <set.h>#include <set.h>

#include <iostream.h>#include <iostream.h>

#include <fstream.h>#include <fstream.h>

const char* delimiters = "\t;()\"<>:{}[]+-=&*#.,/\\~";const char* delimiters = "\t;()\"<>:{}[]+-=&*#.,/\\~";

void main(int argc, char* argv[]) void main(int argc, char* argv[])

{{

ifstream in(argv[1]);ifstream in(argv[1]);

set<string> wordListSet;set<string> wordListSet;

string line;string line;

while(getline(in, line)) while(getline(in, line))

{ {

// Capture individual words:// Capture individual words:

char* token = strtok((char*)line.c_str(), delimiters);char* token = strtok((char*)line.c_str(), delimiters);

Page 45: Standard Template Library

45

Example: Set (contd.)Example: Set (contd.) while(token) while(token)

{{

// Automatic type conversion:// Automatic type conversion:

wordListSet.insert(token);wordListSet.insert(token);

token = strtok(0, delimiters);token = strtok(0, delimiters);

}}

} } // end outer while loop// end outer while loop

ostream_iterator<string> out(cout, "\n")ostream_iterator<string> out(cout, "\n")

// Output results:// Output results:

copy(wordListSet.begin(), wordListSet.end(), out);copy(wordListSet.begin(), wordListSet.end(), out);

} } // end main()// end main()

Page 46: Standard Template Library

46

StackStack

The The stackstack is classified as adapters, is classified as adapters, which means they are implemented which means they are implemented using one of the basic sequence using one of the basic sequence containers: containers: vectorvector, , list list or or dequedeque

The stack has one pointer, which The stack has one pointer, which points to the top of the stackpoints to the top of the stack

You can add (push) or delete (pop) You can add (push) or delete (pop) elements from the top of the stack elements from the top of the stack onlyonly

Page 47: Standard Template Library

47

Example: StackExample: Stack#include <iostream.h>#include <iostream.h>

#include <fstream.h>#include <fstream.h>

#include <stack.h>#include <stack.h>

#include <list.h>#include <list.h>

#include <vector.h>#include <vector.h>

#include <string.h>#include <string.h>

typedef stack<string> Stack1Type; typedef stack<string> Stack1Type; // Default: deque<string>// Default: deque<string>

typedef stack<string, vector<string> > Stack2Type; typedef stack<string, vector<string> > Stack2Type; // Vector// Vector

typedef stack<string, list<string> > Stack3Type; typedef stack<string, list<string> > Stack3Type; // List// List

void main(int argc, char* argv[]) void main(int argc, char* argv[])

{{

ifstream in(argv[1]);ifstream in(argv[1]);

Stack1Type textLines; Stack1Type textLines; // Try the different versions// Try the different versions

// Read file and store lines in the stack:// Read file and store lines in the stack:

string line;string line;

Page 48: Standard Template Library

48

Example: Stack (contd.)Example: Stack (contd.) while(getline(in, line))while(getline(in, line))

textLines.push(line + "\n");textLines.push(line + "\n");

// Print lines from the stack and pop them:// Print lines from the stack and pop them:

while(!textLines.empty()) while(!textLines.empty())

{{

cout << textLines.top();cout << textLines.top();

textLines.pop();textLines.pop();

}}

} } // end main()// end main()

Page 49: Standard Template Library

49

QueueQueue

The The queue queue is a restricted form of a is a restricted form of a deque deque

You can only enter elements at one You can only enter elements at one end, and pull them off the other endend, and pull them off the other end

The The queue queue is an adapter class like is an adapter class like stackstack, in that it is built on top of , in that it is built on top of another sequence containeranother sequence container

Page 50: Standard Template Library

50

Priority QueuesPriority Queues

It’s a special type of queueIt’s a special type of queue When you When you push( ) push( ) an object onto a an object onto a

priority_queuepriority_queue, that object is , that object is sorted into the queue according to a sorted into the queue according to a function or function object function or function object

The The priority_queue priority_queue ensures that ensures that when you look at the when you look at the top( ) top( ) element element it will be the one with the highest it will be the one with the highest priority priority

Page 51: Standard Template Library

51

Priority Queues (contd.)Priority Queues (contd.)

When you’re done with it, you call When you’re done with it, you call pop() pop() to remove it and bring the to remove it and bring the nextnext

one into placeone into place Thus, the Thus, the priority_queue priority_queue has nearly has nearly

the same interface as a the same interface as a stackstack, but it , but it behaves differentlybehaves differently

Page 52: Standard Template Library

52

Example: Priority QueueExample: Priority Queue#include <iostream.h>#include <iostream.h>

#include <queue.h>#include <queue.h>

void main() void main()

{{

priority_queue<int> pqi;priority_queue<int> pqi;

for(int i = 0; i < 100; i++)for(int i = 0; i < 100; i++)

pqi.push(i * 25); pqi.push(i * 25); // Insertion will be sorted// Insertion will be sorted

while(!pqi.empty()) while(!pqi.empty())

{{

cout << pqi.top() << ' ';cout << pqi.top() << ' ';

pqi.pop();pqi.pop();

}}

} }

Page 53: Standard Template Library

53

Associative ContainersAssociative Containers These containers keep {key, value} These containers keep {key, value}

pairs, and store/retrieve data using pairs, and store/retrieve data using associationsassociations

Basic operations with associative Basic operations with associative containers are putting things in:containers are putting things in: In the case of a In the case of a seset, seeing if t, seeing if

something is in the setsomething is in the set In the case of a In the case of a mapmap, you want to first , you want to first

see if a key is in the see if a key is in the mapmap, and if it , and if it exists you want the associated value exists you want the associated value for that key to be returnedfor that key to be returned

Page 54: Standard Template Library

54

MapMap In a In a map map you associate one object with you associate one object with

another in an array-like fashionanother in an array-like fashion Instead of selecting an array element Instead of selecting an array element

with a number, you look it up with an with a number, you look it up with an objectobject

In a In a mapmap, you’ve got two things: the , you’ve got two things: the key key and the and the value value that results from the that results from the lookup with the key lookup with the key

If you simply want to move through If you simply want to move through the entire the entire map map and list each key-value and list each key-value pair:pair:

Page 55: Standard Template Library

55

Map (contd.)Map (contd.)

You use an iterator, which when You use an iterator, which when dereferenced produces a dereferenced produces a pair pair object object containing both the key and the valuecontaining both the key and the value

You access the members of a You access the members of a pair pair by by selecting selecting first first or or secondsecond

A Map may have duplicate keys, and A Map may have duplicate keys, and that is called a Multi-Mapthat is called a Multi-Map

Page 56: Standard Template Library

56

Example: MapExample: Map#include <string>#include <string>

#include <fstream>#include <fstream>

#include <map>#include <map>

typedef map<string, string> DataMapType;typedef map<string, string> DataMapType;

void main()void main()

{{

ifstream in("myFile.db");ifstream in("myFile.db");

DataMapType dMap;DataMapType dMap;

string line;string line;

while(getline(in, line))while(getline(in, line))

{{

int pos = line.find(";");int pos = line.find(";");

string meta = line.substr(0, pos);string meta = line.substr(0, pos);

string data = line.substr(pos+1, line.size());string data = line.substr(pos+1, line.size());

dMap[meta]=data;dMap[meta]=data;

}}

}}

Page 57: Standard Template Library

57

Multi-SetMulti-Set

The The Multi-Set Multi-Set allows more than one allows more than one object of each value to be insertedobject of each value to be inserted

It has more than one object of the It has more than one object of the same value in a set same value in a set

The objects look the same, but they The objects look the same, but they actually contain some differing actually contain some differing internal stateinternal state

Page 58: Standard Template Library

58

Container ConceptsContainer Concepts

Can inherit container classes to Can inherit container classes to achieve the extra functionality, the achieve the extra functionality, the container providescontainer provides

Can combine container classes to Can combine container classes to achieve multi-functional goalsachieve multi-functional goals

Can create templates of clean-up Can create templates of clean-up container pointers (since that’s not container pointers (since that’s not automatic)automatic)

Page 59: Standard Template Library

59

Creating Custom Creating Custom ContainersContainers

You can create your own custom You can create your own custom containerscontainers

Follow the same model of Follow the same model of containers, by providing:containers, by providing: IteratorsIterators Using primitive data typesUsing primitive data types Using library object typesUsing library object types Providing your own object data typesProviding your own object data types

Page 60: Standard Template Library

60

STL AlgorithmsSTL Algorithms

They are templatized functions They are templatized functions designed to work with the containersdesigned to work with the containers

The STL was originally designed The STL was originally designed around the algorithms around the algorithms

The goal was that you use The goal was that you use algorithms for almost every piece of algorithms for almost every piece of code that you writecode that you write

Page 61: Standard Template Library

61

Function ObjectsFunction Objects

A function object has an overloaded A function object has an overloaded operator()operator()

The result is that a template function The result is that a template function can’t tell whether you’ve handed it a can’t tell whether you’ve handed it a pointer to a function or an object that pointer to a function or an object that has an has an operator()operator()

All the template function knows is that it All the template function knows is that it can attach an argument list to the object can attach an argument list to the object as ifas if it were a pointer to a functionit were a pointer to a function

Page 62: Standard Template Library

62

Example: Function Example: Function ObjectsObjects#include <iostream.h>#include <iostream.h>

template<class UnaryFunc, class T>template<class UnaryFunc, class T>

void CallFunc(T& templateElement, UnaryFunc uFunc) void CallFunc(T& templateElement, UnaryFunc uFunc)

{{

uFunc(templateElement);uFunc(templateElement);

}}

void Function(int& element) void Function(int& element)

{{

element = 47;element = 47;

}}

struct UnaryFunc struct UnaryFunc

{{

void operator()(int& element) void operator()(int& element)

{{

element = 48;element = 48;

}}

};};

Page 63: Standard Template Library

63

Example: Function Objects Example: Function Objects (contd.)(contd.)

void main() void main()

{{

int y = 0;int y = 0;

// This calls the template function ‘Function’ and sets // This calls the template function ‘Function’ and sets

// y = 47// y = 47

CallFunc(y, Function);CallFunc(y, Function);

cout << y << endl;cout << y << endl;

y = 0;y = 0;

// This calls the template function ‘operator’ and// This calls the template function ‘operator’ and

// sets y = 48// sets y = 48

CallFunc(y, UnaryFunc());CallFunc(y, UnaryFunc());

cout << y << endl;cout << y << endl;

}}

Page 64: Standard Template Library

64

Classification of Function Classification of Function ObjectsObjects

Function objects are classified based Function objects are classified based on:on: The number of arguments that their The number of arguments that their

operator() operator() takes: zero, one or two takes: zero, one or two argumentsarguments

The kind of value returned by that The kind of value returned by that operator: a operator: a bool bool or non-or non-bool bool valuevalue

The different classifications are:The different classifications are: GeneratorGenerator UnaryFunctionUnaryFunction

Page 65: Standard Template Library

65

Classification of Function Objects Classification of Function Objects (contd.)(contd.)

BinaryFunctionBinaryFunction PredicatePredicate BinaryPredicateBinaryPredicate StrictWeakOrderingStrictWeakOrdering

Page 66: Standard Template Library

66

STL Algorithms STL Algorithms SummarySummary

STL Algorithms have a wide range of STL Algorithms have a wide range of header files, which cover:header files, which cover: Filling & Generating (values)Filling & Generating (values) Counting (number of elements)Counting (number of elements) Manipulating sequencesManipulating sequences Search & ReplaceSearch & Replace Comparing rangesComparing ranges Removing (elements, values)Removing (elements, values) Sorting (elements, values)Sorting (elements, values)

Page 67: Standard Template Library

67

STL Algorithms Summary STL Algorithms Summary (contd.)(contd.)

Heap operationsHeap operations Numeric algorithms (calculations)Numeric algorithms (calculations)

Page 68: Standard Template Library

68

Fill & GenerateFill & Generate

These algorithms allow you to These algorithms allow you to automatically fill a range with a particular automatically fill a range with a particular valuevalue

Or to generate a set of values for a Or to generate a set of values for a particular range particular range

The “fill” functions insert a single value The “fill” functions insert a single value multiple times into the containermultiple times into the container

The “generate” functions use an object The “generate” functions use an object called a called a generator generator to create the values to to create the values to insert into the containerinsert into the container

Page 69: Standard Template Library

69

Example: Fill & GenerateExample: Fill & Generate#include <vector.h>#include <vector.h>

#include <algorithm.h>#include <algorithm.h>

#include <string.h>#include <string.h>

#include <stdlib.h>#include <stdlib.h>

void main() void main()

{{

randomize();randomize();

vector<string> v1(5);vector<string> v1(5);

fill(v1.begin(), v1.end(), "howdy");fill(v1.begin(), v1.end(), "howdy");

vector<string> v2;vector<string> v2;

fill_n(back_inserter(v2), 7, "bye");fill_n(back_inserter(v2), 7, "bye");

vector<int> v3(10);vector<int> v3(10);

generate(v3.begin(), v3.end(), random(10));generate(v3.begin(), v3.end(), random(10));

vector<int> v4;vector<int> v4;

generate_n(back_inserter(v4),15, random(15));generate_n(back_inserter(v4),15, random(15));

}}

Page 70: Standard Template Library

70

CountingCounting

All containers have a method All containers have a method size() size() that will tell you how many elements that will tell you how many elements they holdthey hold

In the example, the In the example, the set set is used to is used to count all the instances of all the count all the instances of all the different characters, and display different characters, and display themthem

Page 71: Standard Template Library

71

Example: CountingExample: Counting#include <vector.h>#include <vector.h>

#include <algorithm.h>#include <algorithm.h>

#include <stdlib.h>#include <stdlib.h>

void main() void main()

{{

vector<char> v;vector<char> v;

// generates random characters and inserts it into vector// generates random characters and inserts it into vector

generate_n(back_inserter(v), 50, (char)(random(26) + 49));generate_n(back_inserter(v), 50, (char)(random(26) + 49));

// Create a set of the characters in v:// Create a set of the characters in v:

set<char> cs(v.begin(), v.end()); set<char> cs(v.begin(), v.end()); // copies vector in set// copies vector in set

set<char>::iterator it = cs.begin(); set<char>::iterator it = cs.begin(); // set iterator// set iterator

while(it != cs.end()) while(it != cs.end()) // loop till end of set reached// loop till end of set reached

{{

int n = count(v.begin(), v.end(), *it);int n = count(v.begin(), v.end(), *it);

cout << *it << ": " << n << ", ";cout << *it << ": " << n << ", ";

it++;it++;

}}

Page 72: Standard Template Library

72

Example: Counting Example: Counting (contd.)(contd.)

int lc = count_if(v.begin(), v.end(), int lc = count_if(v.begin(), v.end(), bind2nd(greater<char>(), 'a'));bind2nd(greater<char>(), 'a'));

cout << "\nLowercase letters: " << lc << endl;cout << "\nLowercase letters: " << lc << endl;

} } // end main()// end main()

Page 73: Standard Template Library

73

Manipulating SequencesManipulating Sequences

Following algorithms allows to work Following algorithms allows to work with sequences:with sequences: copycopy copy_backwardcopy_backward reversereverse reverse_copyreverse_copy swap_rangesswap_ranges

Page 74: Standard Template Library

74

Search & ReplaceSearch & Replace

Following algorithms are used to search Following algorithms are used to search and replace elements in containers:and replace elements in containers: findfind find_iffind_if adjacent_findadjacent_find find_first_offind_first_of searchsearch find_endfind_end search_nsearch_n

Page 75: Standard Template Library

75

Search & Replace Search & Replace (contd.)(contd.)

min_elementmin_element max_elementmax_element replacereplace

Page 76: Standard Template Library

76

Example: Search & Example: Search & ReplaceReplace#include <vector.h>#include <vector.h>

#include <algorithm.h>#include <algorithm.h>

#include <functional.h>#include <functional.h>

void main() void main()

{{

int a[] = { 1, 2, 3, 4, 5, 6, 6, 7, 7, 7,int a[] = { 1, 2, 3, 4, 5, 6, 6, 7, 7, 7,

8, 8, 8, 8, 11, 11, 11, 11, 11 };8, 8, 8, 8, 11, 11, 11, 11, 11 };

const int asz = (sizeof a) * (sizeof *a);const int asz = (sizeof a) * (sizeof *a);

vector<int> v(a, a + asz);vector<int> v(a, a + asz);

// This finds the value 4 in v// This finds the value 4 in v

vector<int>::iterator it = find(v.begin(), v.end(), 4);vector<int>::iterator it = find(v.begin(), v.end(), 4);

// use find_if to return iterator to second occurrence of // use find_if to return iterator to second occurrence of

// 11 in the vector (greater than 8)// 11 in the vector (greater than 8)

it = find_if(v.begin(), v.end(), it = find_if(v.begin(), v.end(),

bind2nd(greater<int>(), 8));bind2nd(greater<int>(), 8));

// it finds the first identical values, which are adjacent// it finds the first identical values, which are adjacent

Page 77: Standard Template Library

77

Example: Search & Replace Example: Search & Replace (contd.)(contd.)

// e.g. first 6 in vector given above// e.g. first 6 in vector given above

it = adjacent_find(v.begin(), v.end());it = adjacent_find(v.begin(), v.end());

int b[] = { 8, 11 };int b[] = { 8, 11 };

const int bsz = (sizeof b) * (sizeof *b);const int bsz = (sizeof b) * (sizeof *b);

// It finds first matching value in v having value ‘b+bsz’// It finds first matching value in v having value ‘b+bsz’

it = find_first_of(v.begin(), v.end(), b, b + bsz);it = find_first_of(v.begin(), v.end(), b, b + bsz);

// Finds exactly the second range inside the first one, // Finds exactly the second range inside the first one,

// with the elements in the same order.// with the elements in the same order.

it = search(v.begin(), v.end(), b, b + bsz);it = search(v.begin(), v.end(), b, b + bsz);

int d[] = { 11, 11, 11 };int d[] = { 11, 11, 11 };

const int dsz = (sizeof d) * (sizeof *d);const int dsz = (sizeof d) * (sizeof *d);

// Finds the // Finds the last last occurrence of the entire sequence occurrence of the entire sequence

it = find_end(v.begin(), v.end(), d, d + dsz);it = find_end(v.begin(), v.end(), d, d + dsz);

// Looks for 3 copies of the value 7// Looks for 3 copies of the value 7

it = search_n(v.begin(), v.end(), 3, 7);it = search_n(v.begin(), v.end(), 3, 7);

vector<int> v2;vector<int> v2;

Page 78: Standard Template Library

78

Example: Search & Replace Example: Search & Replace (contd.)(contd.)

// Replaces the specified values in a new vector// Replaces the specified values in a new vector

replace_copy(v.begin(), v.end(), back_inserter(v2), 8, replace_copy(v.begin(), v.end(), back_inserter(v2), 8, 47);47);

// Replaces 7 or values greater than 7 with -1// Replaces 7 or values greater than 7 with -1

replace_if(v.begin(), v.end(), replace_if(v.begin(), v.end(), bind2nd(greater_equal<int>(), 7), -1);bind2nd(greater_equal<int>(), 7), -1);

} } // end main()// end main()

Page 79: Standard Template Library

79

Comparing RangesComparing Ranges

These algorithms provide ways to These algorithms provide ways to compare two rangescompare two ranges

The different comparison operations The different comparison operations are:are: equalequal lexicographical_comparelexicographical_compare mismatchmismatch

Page 80: Standard Template Library

80

Example: Comparing Example: Comparing RangesRanges#include <vector.h>#include <vector.h>

#include <algorithm.h>#include <algorithm.h>

#include <functional.h>#include <functional.h>

#include <string.h>#include <string.h>

void main() void main()

{{

string s1("This is a test");string s1("This is a test");

string s2("This is a Test");string s2("This is a Test");

equal(s1.begin(), s1.end(), s2.begin());equal(s1.begin(), s1.end(), s2.begin());// compare s1 & s2// compare s1 & s2

lexicographical_compare(s1.begin(), s1.end(), s2.begin(), lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end()); s2.end()); // ASCII value comparison// ASCII value comparison

// This prints the string characters that don’t match in // This prints the string characters that don’t match in

// both the strings// both the strings

pair<string::iterator, string::iterator> p =pair<string::iterator, string::iterator> p =

mismatch(s1.begin(), s1.end(), s2.begin()); mismatch(s1.begin(), s1.end(), s2.begin());

print(p.first, s1.end(), "p.first", "");print(p.first, s1.end(), "p.first", "");

print(p.second, s2.end(), "p.second","");print(p.second, s2.end(), "p.second","");

}}

Page 81: Standard Template Library

81

Removing elements from a Removing elements from a containercontainer

Because of the genericity of the STL, Because of the genericity of the STL, the concept of removal is a bit the concept of removal is a bit constrained constrained

Elements can only be “removed” via Elements can only be “removed” via iteratorsiterators

It is not safe or reasonable to It is not safe or reasonable to actually try to destroy the elements actually try to destroy the elements that are being removed, and to that are being removed, and to change the size of the input range change the size of the input range

Page 82: Standard Template Library

82

Removing Elements Removing Elements (contd.)(contd.) The STL “remove” functions:The STL “remove” functions:

Rearrange the sequence so that the Rearrange the sequence so that the “removed” elements are at the end of the “removed” elements are at the end of the sequencesequence

The “un-removed” elements are at the The “un-removed” elements are at the beginning of the sequence beginning of the sequence

function will return an iterator to the function will return an iterator to the “new last” element of the sequence, “new last” element of the sequence, which is the end of the sequence without which is the end of the sequence without the removed elements the removed elements

function will return the beginning of the function will return the beginning of the sequence of the removed elementssequence of the removed elements

Page 83: Standard Template Library

83

Example: Removing Example: Removing ElementsElements

#include <vector.h>#include <vector.h>

#include <algorithm.h>#include <algorithm.h>

void main() void main()

{{

vector<char> v(50);vector<char> v(50);

generate(v.begin(), v.end(), (char) (random(26)+49));generate(v.begin(), v.end(), (char) (random(26)+49));

vector<char>::iterator cit;vector<char>::iterator cit;

// Step through and remove everything:// Step through and remove everything:

while(cit != v.end()) while(cit != v.end())

{{

cit = remove(v.begin(), v.end(), *cit);cit = remove(v.begin(), v.end(), *cit);

cout << *cit;cout << *cit;

cit++;cit++;

}}

Page 84: Standard Template Library

84

Example: Removing Elements Example: Removing Elements (contd.)(contd.)

cit = remove_if(v.begin(), v.end(), isUpper());cit = remove_if(v.begin(), v.end(), isUpper());

vector<char> v2;vector<char> v2;

unique_copy(v.begin(), cit, back_inserter(v2));unique_copy(v.begin(), cit, back_inserter(v2));

} } // end main()// end main()

Page 85: Standard Template Library

85

SortingSorting There is actually only one “sort” There is actually only one “sort”

algorithm used in the STL algorithm used in the STL This algorithm is presumably the This algorithm is presumably the

fastest onefastest one The different types of sorting are:The different types of sorting are:

sortsort stable_sortstable_sort partial_sortpartial_sort partial_sort_copypartial_sort_copy nth_elementnth_element

Page 86: Standard Template Library

86

Example: SortingExample: Sorting#include <deque.h>#include <deque.h>

#include <iostream.h>#include <iostream.h>

#include <sort.h>#include <sort.h>

#include <vector.h>#include <vector.h>

void main(int argc, char* argv[]) void main(int argc, char* argv[])

{{

ifstream in(argv[1]);ifstream in(argv[1]);

StreamTokenizer words(in); StreamTokenizer words(in); // used to delimit elements// used to delimit elements

deque<string> nstr;deque<string> nstr;

string word;string word;

while((word = words.next()).size() != 0)while((word = words.next()).size() != 0)

nstr.push_back(string(word));nstr.push_back(string(word)); // add to deque// add to deque

// Create a vector from the contents of nstr// Create a vector from the contents of nstr

vector<string> v(nstr.begin(), nstr.end());vector<string> v(nstr.begin(), nstr.end());

sort(v.begin(), v.end());sort(v.begin(), v.end()); // sort the elements// sort the elements

print(v, "sort");print(v, "sort"); // print the sorted elements// print the sorted elements

}}

Page 87: Standard Template Library

87

Heap OperationsHeap Operations The heap operations in the STL are The heap operations in the STL are

primarily concerned with the creation primarily concerned with the creation of the STL of the STL priority_queupriority_queuee

It provides efficient access to the It provides efficient access to the “largest” element (can be set in code)“largest” element (can be set in code)

The different heap operations are:The different heap operations are: make_heapmake_heap push_heappush_heap pop_heappop_heap sort_heapsort_heap

Page 88: Standard Template Library

88

Creating Your Own STL-Style Creating Your Own STL-Style AlgorithmsAlgorithms

The easiest way to create STL-style The easiest way to create STL-style algorithms is:algorithms is: Goto the <algorithm> header file of Goto the <algorithm> header file of

STLSTL Search the closest implementation of Search the closest implementation of

what you needwhat you need Copy the file, and rename it to your own Copy the file, and rename it to your own

name (e.g. myalgo.h)name (e.g. myalgo.h) Make the necessary changes to the fileMake the necessary changes to the file

Page 89: Standard Template Library

89

Example: Custom STL Example: Custom STL AlgorithmAlgorithm

//: copy_if.h//: copy_if.h

// Your own STL-style algorithm// Your own STL-style algorithm

#ifndef COPY_IF_H#ifndef COPY_IF_H

#define COPY_IF_H#define COPY_IF_H

template<typename ForwardIter, typename OutputIter, template<typename ForwardIter, typename OutputIter, typename UnaryPred> typename UnaryPred>

OutputIter copy_if(ForwardIter begin, ForwardIter end,OutputIter copy_if(ForwardIter begin, ForwardIter end,

OutputIter dest, UnaryPred f) OutputIter dest, UnaryPred f)

{{

while(begin != end) while(begin != end)

{{

if(f(*begin))if(f(*begin))

*dest++ = *begin;*dest++ = *begin;

begin++;begin++;

}}

return dest;return dest;

}}

#endif #endif // COPY_IF_H// COPY_IF_H

Page 90: Standard Template Library

90

Unit SummaryUnit Summary

In this unit you have covered …In this unit you have covered … Standard template libraryStandard template library Different features of STLDifferent features of STL In-depth knowledge of some of the In-depth knowledge of some of the

library features like string, library features like string, containers etccontainers etc