Anda di halaman 1dari 82

UNIT III

C++ PROGRAMMING ADVANCED FEATURES 9


Abstract class Exception handling - Standard libraries - Generic
Programming - templates class template - function template STL
containers iterators function adaptors allocators - Parameterizing
the class - File handling concepts.

Exception handling Errors


Errors are produced while we writing
a program.
Errors are classified into 3 major
categories. They are
A) syntax error
B) logical error
C) exception or runtime error
2

Syntax error:
This type of error occurs when the user
violates the languages rule and
regulations.
(e.g) cout>>enter the number; invalid
Cout<<enter the number; valid

Logical error:
this type of error occurs when the
programmer violates the logical concepts
of the language. These errors can be
identified only by the wrong output for the
right input.
3

ERROR (Exception) HANDLING


The exception refers to unexpected condition in a program and
occurs during the run time.
The unexpected conditions could be faults, causing an error
which in turn causes the program to fail.
The error handling mechanism of C++ is generally referred to
as exception handling.
Types of Exceptions
Synchronous Exception
Asynchronous Exception
Synchronous Exception
The exception which occurs during the program execution,
due to some fault in the input data or technique that is not
suitable to handle the current class of data, with in the
program are known as synchronous exception.
Example: out of range, divide by zero, overflow,
underflow, running out of memory.

Asynchronous Exception
The errors that are caused by events beyond the control of
the program are called asynchronous exceptions.
Example: disk failure
keyboard problems etc
All the synchronous exceptions occur within the program
control. But the asynchronous exceptions occur beyond the
program control.
USES:
It avoids abnormal situation during run time.
It help the user by reporting the reason for abnormal
conditions so that the appropriate action will be taken.
5

Exception handling Mechanism:


The purpose of the exception handling mechanism is to
provide means to detect and report an exceptional
circumstance so that appropriate action can be taken.
The exception handling mechanism consists of the
following task or operations:

Find the problem ( hit the exception)


Inform that an error has occurred (throw the exception)
Receive the error information ( catch the exceptions)
Take corrective actions( handle the exceptions)

Try Block:
This block contains ordinary C++ statements and it is related
to throw blocks. The important task of try block is to find out
the abnormal conditions for the given statements. Then the
throw block throws the exception objects.

Throw block:
This block is used to throw the detected exception objects.
you use a throw expression to indicate that your program has
encountered an exception

Catch Block:
A catch block is defined by the keyword catch which cathces
the exceptions thrown by the throw statement in the try block
and handle it appropriately.

Error handling basically consists of two


segments:
One to detect and to throw exceptions
Other to catch the exceptions and to take
appropriate actions.
Exception Handling Model:

The exception handling mechanism uses three


blocks try, throw, catch. The relationship of those
three exception handling model shown below
Try block
Diagram:
Detects and throws an exception

Exception
object
Catch block
Catches and handles the exception

The keyword try is used to preface a block of statements (surrounded by


braces) which may generate exceptions. This block of statements known as
try block.
When an exception is detected, it is thrown using a throw statement in the
try block.
A catch block defined by the keyword catch catches the exception thrown
by the throw statement in the try block, and handle it appropriately.
General format:

try
{
.
// block of statements which detects and
throw exception // throws an exception
.
}
catch ( type arg)
{

// block of statements that handles the


exception

}
..
}

When the try block throws an exception, the program control leaves the
try block and enters the catch statement of the catch block.
Exceptions are objects or variables used to transmit information about a
problem.
If the type of object thrown matches the arg type in the catch statement,
then catch block is executed for handling the exception.
If they do not match, the program is aborted with the help of the abort()
function which is invoked automatically.
The catch block may have more than one catch statements, each
corresponding to a particular type of exception.
For example if the throw block is likely to throw two exception, the
catch block will have two catch statements one for each type of
exception. Each catch statement is called is exception handler.
When no exception is detected and thrown, the control goes to the
statement immediately after the catch block. That is catch block is
skipped.

Example: divide by zero

RUN 1:

enter the values of x , y, z


50 30 20
the result of z/ (x-y ) is: 1

#include<iostream.h>
void main( )
{
int x, y, z;
cout<<enter the values of x, y, z;
cin>>x>>y>>z;
try
{
if(x= =y)
throw y;
else
int d= z / ( x- y);
cout<<the result of z/ (x-y )is:<< d;
}
catch( int y)
{
cout<<exception caught x-y is << x-y ;
}
}

MULTIPLE CATCHES WITH OBJECT:


To throw an exception with an object it needs to define an abstract class.
Abstract class is nothing but a class with empty data members and member
functions..
Class name is called as nameless object which is used to throw the exceptions
Example:
#include<iostream.h>
class positive { };
class negative { };
class zero { };
void greater ( int num)
{
if( num >0)
throw positive( );
else
if (num < 0)
throw negative( );
else
throw zero( );
}

void main( )
{
int num;
cout<<enter any number;
cin>>num;
try
{
greater ( num);
}
catch( positive)
{
cout<<+ve exception;
}
catch(negative)
{
cout<<-ve exception;
}
catch (zero)
{
cout<<0 exception;
}
}

CATCH ALL EXCEPTION


In such circumstances, we can force a catch statement to catch all
exceptions instead of a certain type alone. it should always be placed last in the
list of handlers.
catch()
{
statement for processing all exceptions
}
#include<iostream.h>
void test(int x)
{
try
{
if(x==0) throw x;
if(x==-1) throw x;
if(x==1) throw 1.0;
}
catch()
{
cout<<caught an exception \n;
}
};

int main()
{
cout<<testing generic catch \n;
test(-1);
test(0);
test(1);
}

RETHROWING AN EXCEPTION

a handler may decide to throw the exception caught without processing it. it
invokes throw without any argument
int main()
ex: throw;
{
#include<iostream.h>
cout<<inside main;
void divide(double x, double y)
try
{
{
divide(10.5,2.0);
cout<<inside function \n;
divide(20.0,0.0);
try
}
{
catch(double)
if(y==0.0)
{
throw y;
cout<<caught double inside main\n;
else
cout<<division = <<x/y;
}
}
cout<<end of main \n ;
}
catch(double)
{
cout<<caught double inside function \n;
throw;
}
cout<<end of function \n ;
}

EXCEPTION SPECIFICATION

It is possible to restrict a function to throw only certain specified


exceptions.
General form of exception specification is:
type function(arglist) throw(type_list)
{
Function body
}
Throwing any other type of exception will cause program
termination.
If we want to prevent function from throwing any exception, we
may do so by making the type_list empty.
Syntax:
throw();
example
catch(int m)
void check(int x) throw(int) int main()
{
{
{
cout<<caught integer
if(x==0) throw x;
try
exception;
else
{
}
if(x==1) throw x;
check(1);
catch(char c)
}
}
{
cout<<caught char exception;
}

Uncaught exceptions

If a propagating exceptionis not caught by anytrycatch"net", then it propagates all the way out ofmain()

In that case the program terminates, usually with an


"uncaught exception" error message.

16

TEMPLATES
Templates
Templates are a feature of the C++ programming language
that allow functions and classes to operate with generic types.
This allows a function or class to work on many different data
types without being rewritten for each one.
Generic Programming
Is an approach where generic types are used as parameters
in algorithms
Generic programs work for a variety of suitable data types
and data structures

A template can be used to create a


family of classes or functions
Example:

template for an array enable us to create arrays of


various data types such as int array and float array
template for a function, say mul() helps us for
multiplying int, float and double type values

Template is defined with a parameter


that would be replaced by a specified
data type at the time of actual use of the
class or function, the templates are
sometimes called parameterized classes
or function

Template Definition:
template<class T>
The prefix tells the compiler that we are going
to declare a template and use T as a type name
in the declaration
The type T may represent a class name .
A class created from a class template is called a
template class
Syntax for defining an object of a template class
is:
classname<type> objectname(arglist);
This process of creating a specific class from a
class template is called instantiation.

CLASS TEMPLATES
Example program for template using single parameters
# include <iostream.h>
template<class T >
Class sample
{
Private:
T value;
Public:
Void read()
{
Cout<<enter values;
Cin>>value;
}
Void display()
{
Cout<<value=<<value;
}
};

void main()
{
Sample<int>s1;
Sample <float>s2;
S1.read();
S1.display();
S2.read();
S2.display();
}
Output:
Enter values 10
Value=10
Enter values 10.5
Value=10.5

# include <iostream.h>
# include <string.h>
template<class T >
Class sample
{
Private:
T a;
T b;
Public:
Void read()
{
Cout<<enter values;
Cin>>a>>b;
}
Void display()
{
Cout<<value=<<a<<b;
}
};

Example:2
void main()
{
Sample<int,int>s1;
Sample <float,float>s2;
S1.read();
S1.dispaly();
S2.read();
S2.dispaly();
}
Enter values 10 20
Value=10 20
Enter values 10.5 20.5
Value=10.5 20.5

CLASS TEMPLATES WITH MULTIPLE


PARAMETERS

Can use more than one generic data type in a class


template
They are declared as a comma separated list within the
template specification

Example program for


template using Multiple
parameters
# include <iostream.h>
# include <string.h>
template<class T1,class T2 >
class sample
{
private:
t1 a, z;
t2 b;
public:
void read()
{
cout<<enter values;
cin>>a>>b;
z=a+b;
}

void display()
{
cout<<value=<<z;
}
};
void main()
{
sample<float ,int>s1;
s1.read();
s1.dispaly();
getch();
}
Output:
Enter values 10.3 20
Value=30.3

Function template

Like class templates, we can also define function templates that could be
used to create a family of functions with different argument types.
The function template syntax is similar to that of class template except that
we are defining functions instead of classes.
We must use the template parameter T as and when necessary in the
function body and its argument list. The general format of a function
template is:
Syntax:
template<class T>
return type function name (arguments of type T)
{
//
//body of function //with type T
//wherever appropriate
//..
}

The following example declares a swap() function template that will swap
two values of a given type of data.
template<class T>
void swap(T &x,T &y)
{
T temp=x;
X=Y;
Y=temp;
}

Here is another example where a function template returns


a value.
template<class T>
T max(T x, T y)
{
Return x>y ?x:y;
}

FUNCTION TEMPLATES
# include <iostream.h>
# include <string.h>
template<class T >
void display(T x)
{
cout << x;
}
void main()
{
display(1999);
display(12.34);
display(w);
return 0;
}
OUTPUT:
1999
12.34
w

# include <iostream.h>
# include <string.h>
template<class T >
void display(T x, T y)
{
cout << x<<y;
}
int main()
{
display(1999,2000);
display(12.34,10.5)
display(w,s);
return 0;
}

OUTPUT:
1999 2000
12.34 10.5
ws

Example for swapping two int and float values


#include<iostream.h>
#include<conio.h>
template<class T>
void swap(T&x,T&y)
{
T temp=x;
X=Y;
Y=temp;
}
void main()
{
clrscr();
int a=10,b=20;
cout<<Before
swapping:<<endl;

cout<<a=<<a<<endl<<
b=<<b<<endl;
swap(a,b);
cout<<After
swapping:<<endl;
cout<<a=<<a<<endl<<
b=<<b<<endl;
char c1=$,c2=&;
cout<<Before
swapping:<<endl;
cout<<c1=<<c1<<endl<
<c2=<<c2<<endl;

swap(c1,c2);
cout<<After
swapping:<<endl;
cout<<c1=<<c1<<end
l<<c2=<<c2<<endl;
float f1=3.45,f2=4.65;
cout<<Before
swapping:<<endl;
cout<<f1=<<f1<<endl
<<f2=<<f2<<endl;
swap(f1,f2);

cout<<After
swapping:<<endl;
cout<<f1=<<f1<<en
dl<<f2=<<f2<<en
dl;
getch();
}

FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS


FUNCTION WITH TWO GENERIC TYPES
# include <iostream.h>
# include <string.h>
template<class T1, class T2>
void display(T1 x, T2 y)
{
cout << x << " " << y << "\n";
}
int main()
{
display(1999, "EBG");
display(12.34, 1234);
return 0;
}
OUTPUT:
1999 EBG
12.34 1234

MEMBER FUNCTION TEMPLATES

# include <iostream.h>
template<class T >
Class sample
{
Private:
T value;
public:
void read()
void display()
};
template<class T >
void sample <t>:: read()
{
cout<<enter values;
cin>>value;
}

template<class T >
void sample<t>::display()
{
cout<<value=<<value;
}
void main()
{
sample<int>s1;
sample <float>s2;
s1.read();
s1.dispaly();
s2.read();
s2.dispaly();
}

Output:
Enter values 10
Value=10
Enter values 10.5
Value=10.5

FILE HANDLING
FUNCTIONS

The information / data stored

under a specific name on a


storage device, is called a file.

{OR}
A file is a collection of related
data stored in a particular area
on the disk.

WORKING WITH FILES

To handle large volumes of data we can use


storage devices to store the data.
The data is stored in these devices using the
concept of files.
Programs can be designed to perform the
read and write operations
TYPES OF FILES:
SEQUENTIAL ACCESS FILE
RANDOM ACCESS FILEon these files.

TEXT MODE

BINARY MODE

It is a file that stores


It is a file that
information in ASCII
contains
characters.
information in the
Each line of text is
same format as it
terminated with a
is held in memory.
special character
known as EOL (End of In binary files, no
delimiters are
Line) character or
used for a line.
delimiter character.
When EOL character No translations
occur here.
is read or written,
certain internal
translations take place

A program typically involves


either or both of the following
kinds of data communication:
1.Data transfer between the program
and a disk file.
2.Data transfer between the console
unit and the program.
The input stream extracts (or
reads) data from the file and the
output stream inserts (or writes)
data to the file.

CLASSES FOR FILE STREAM


OPERATIONS
These include ifstream, ofstream and
fstream.
These classes, designed to manage the disk
files, are declared in fstream and therefore
we must include this file in any program that
uses files.

OPENING AND CLOSING A FILE


To use a disk file, we need to
decide the following about the file:
1. Suitable name for the file.
2. Data type and structure.
3. Purpose.
4. Opening method

A file can be opened in two ways:


1. Using the constructor function
of the class.
2. Using the member function
open () of the class.
The first method is useful when we use
only one file in the stream.
The second method used
when we want to manage multiple files
using one stream.

OPENING FILES USING CONSTRUCTOR


A constructor is used to initialize an object while it is being
created. A filename is used to initialize the file stream object .
This involves the following steps:
1. Create a file stream object to manage the stream using the
appropriate class. That is to
say, the class ofstream is used to create the output stream
and the class ifstream to
create the input stream.
2. Initialize the file object with the desired filename.
For example, the following statement opens a file named
results for output:

Ofstream stream_obj(results); // output only

Similarly, the following statement declares infile as an


ifstream object and attaches it to the file data for reading
(input).

Ifstream stream_obj(data);//input only

Opening files using constructor method


Program:
#include<iostream.h>>
#include<fstream.h>
int main()
{
ofstream outf(details");
char name[20];
int no;
cout<<"enter name and no";
cin>>name>>no;
outf<<name<<"\n"<<no<<"\n";
outf.close();
ifstream inf(details");
inf>>name>>no;
cout<<"name="<<name<<"\n"<<"no="<<no;
inf.close();
return 0;
Output:
}

enter name and no


anirudh
16
name=anirudh
no=16

OPENING FILES USING OPEN()

The function open() can be used to open multiple files


that use the same stream object. For
example, we may want to process a set of files
sequentially.
File-stream-class stream-object;
Stream-object.open (filename);
example:
ofstream fout;
fout.open("country");

file-stream class is ofstream


Stream-object is fout

Opening file using open() member function


Program:
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
ofstream fout;
fout.open("country");
fout<<"\nIndia"<<"\n";
fout<<"Pakistan"<<"\n";
fout<<"Srilanka"<<"\n";
fout.close();
fout.open("capital");
fout<<"\nDelhi"<<"\n";
fout<<"Karachi"<<"\n";
fout<<"Kolumbo"<<"\n";
fout.close();

const int n=80;


char line[n];
ifstream fin;
fin.open("country");
cout<<"\ncontents of country
file";
while(fin)
{
fin.getline(line,n);
cout<<line;
}
fin.close();
fin.open("capital");
cout<<"\ncontents of capital file";
while(fin)
{

fin.getline(line,n);
cout<<line;
}
fin.close();
getch();
}

Output
contents of country file
IndiaPakistanSrilanka
contents of capital file
DelhiKarachiKolumbo

FILE MODES IN open() function:


The general form of the function open() with two
arguments is:
Stream-object. Open (filename, mode);
The second argument mode ( called file mode parameter)
specifies the purpose for which the file is opened.
The prototype of these class member functions contain
default values for the second argument and they use the
default values in the absence of the actual values. The default
values are as follows:

ios::in ifstream functions meaning open for reading only


ios::out ofstream functions meaning open for writing
only
The file mode parameter can take one (or more) of such
constants defined in the class ios.

FILE POINTERS AND THEIR MANIPULATIONS


Each file has two associated pointers known as the file
pointers:
Input pointer(get pointer)
Output pointer(put pointer)
These pointers are used to move through the files while
reading or writing.
The input pointer is used for reading the contents of a
given file location and the output pointer is used for writing to
a given file location.
Default actions
A file in read only mode, the input pointer is automatically
set at the beginning start to read from start.
A file in write-only mode, the existing contents are deleted
and the output pointer is set at the beginning to write to the
file from the start.
To open an existing file to add more data, the file is open in
appendmode. This moves the output pointer to the end of the
file.

Functions of manipulation of file


pointers

The file stream classes support the following


functions to manage such situations:
o seekg() moves get pointer(input) to a specified
location.
o seekp() moves put pointer(output) to a
specified location.
o tellg() gives the current position of the get
pointer.
o tellp() gives the current position of the put
pointer.
int_type variable_name=file_obj.tellp();
example:
int p=fileobj.tellp();

To move a file pointer to a desired location using the seek functions. The argument
to these functions represent the absolute position in the file.
seek functions seekg() and seekp() can also be used with two arguments

Seekg (offset, refposition);


Seekp (offset, refposition);
The parameter offset represents the number of bytes the file pointer is to be moved
from the location specified by the parameter refposition.
The seekg() function moves the associated files get pointer and the seekp() function
moves the associated files put pointer.

Sequential input and output operations

the file stream classes support a number of


member functions for performing the input and
output operations on files.
put() and get(), are designed for handling a single
character at a time.
write() and read(), are designed to write and read
blocks of binary data.
Put() and get() functions
put()
writes a single character to the output stream.
get()
reads a single character from the input stream.

Program:
#include<iostream.h>
Output:
Enter a string
#include<fstream.h>
Cobol_programming input
#include<string.h>
Cobol_programming output
int main()
{
char string[80];
cout<<Enter a string\n;
cin>>string;
int len=strlen(string);
fstream file;
\\ input and output stream
file.open(TEXT,ios::in| ios::out);
for(int i=0,i<len;i++)
file.put(string[i]); \\ put a character to file
file.seekg(0);
\\ go to start
char ch;
while(file)
{
file.get(ch); \\ get a character from a file
cout<<ch;
\\ display it on screen
}
return 0;}

Write() and read() functions:


The function write() and read(), unlike the
functions put() and get(),they handle the
data in binary form.
This means that values are stored in the
disk file in the same format in which they
are stored in the internal memory.The
binary input and output functions takes the
following form:

Infile.read((char*)&v, sizeof(v));

Outfile.write((char*)&v,sizeof(v));

for(i=0;i<4;i++)
I/O operations on binary files:
{
Program:
cout.setf(ios::showpoint);
#include<iostream.h>
cout<<setw(10)<<setprecision(2)<<hei
#include<conio.h>
ght[i];
#include<iomanip.h>
}
const char * filename= binary;
infile.close();
int main()
return 0;}
{
float height[4] ={175.5,153.0,167.25,160.70}
ofstream outfile;
outfile.open(filename);
outfile.write((char*)&height, sizeof(height));
outfile.close(); \\ close the file for reading
for (int i=0;i<4;i++) \\ clear array from memory
height[i]=0;
ifstream infile;
infile.open(filename);
infile.read((char*)&height, sizeof(height));

Output:
175.50 153.00 167.25

RANDOM ACCESS IN FILE

Updating a file:
Updating is a routine task in the maintenance of any data file. The updating
would include one or more of the following tasks:

Displaying the contents of a file.


Modifying the existing item.
Adding a new item.
Deleting an existing item.
The size of each object can be obtained using the statement
int object_length=sizeof(object);
The location of the desired object, say the mth object, may be obtained
as follows:
int location =m * object_length;
The location gives the byte number of the first byte of the mth object.
Now, we can set the file pointer to reach this byte with the help of seekg()
or seekp().
The total number of objects in a file using the object_length as follows:
int n=
file_size/object_length;
operations on the file:
1. Adds the new item to the file.
2. Modifies the details of an item.

DETECTING END-OF-FILE

In While (fin),the while loop terminate when fin returns


a value of zero on reaching the end-of-file condition.

if(fin1.eof() != 0) {exit(1);}

eof() is a member function of ios class. It returns a nonzero value if the end-of-file (EOF) condition is encountered,
and a zero, otherwise.

Example:

ifstream infile;
infile.open(ABC);
while(!infile.fail())
{
. (process when operation fails)
.
}
if (infile.eof())
{
.. (terminate program normally)
}
else
if(infile.bad())
{
.. (report fatal error)
}
else
{
infile.clear(); \\ clear error state

ERROR IN FILE HANDLING

1. A file which we are attempting to open for reading


does not exist.
2. The file name used for a new file may already
exist.
3. We may attempt an invalid operation such as
reading past the end-of-file.
4. There may not be any space in the disk for storing
more data.
5. We may used an invalid filename.
6. We may attempt to perform an operation when the
file is not opened for that purpose

Standard Template Library


The STL provides general purpose, templatized classes and
functions that implement many popular and commonly used
algorithms and data structures.
For example it includes support for vectors,list,queues and stacks. It
also defines various routines that access them.
STL components are now part of the standard c++ Library are
defined in the namespace standard we must therefore use the using
namespace directive.

Advantages
to save the time and effort
to reuse the same code

Components of STL
The three key components of STL are
Containers
Algorithms
Iterators
A container is an object that actually stores data in memory, for
example an array of elements.
Algorithms in the STL are procedures that are applied to containers
to process their data, for example search for an element in an array,
or sort an array.
Iterators are a generalization of the concept of pointers, they point
to elements in a container, for example you can increment an
iterator to point to the next element in an array

Containers, Iterators,
Algorithms
Algorithms use iterators to interact with objects
stored in containers
Container
Container
Iterator

Algorithm
Iterator

Objects
Iterator

Algorithm

Algorithm

Iterator

Containers
Containers are objects that hold data, either built-in data
types like int and float, or class objects.
STL containers are implemented by template class.
Each container class defines the set of functions that
can be used to manipulate its contents.
The STL provides several basic kinds of containers
the major 3 categories,
sequence container
<vector> : one-dimensional array
<list> : double linked list
<deque> : double-ended queue
Derived container
<queue> : queue
<stack> : stack
Associative container
<set> : set
<map> : associative array
<priority queue>

Sequence Containers
A sequence container stores a set of elements in sequence, in
other words each element (except for the first and last one) is
preceded by one specific element and followed by another,
<vector>,<list> and <deque> are sequential containers
STL provides three types of sequence containers.
In an ordinary C++ array the size is fixed and can not change
during run-time, it is also tedious to insert or delete elements.
Advantage: quick random access
<vector> is an expandable array that can shrink or grow in size,
but still has the disadvantage of inserting or deleting elements in
the middle . It allows insertion and deletion at back.

Sequence Containers
<list> is a double linked list (each element has points to its
successor and predecessor), it is quick to insert or delete
elements but has slow random access
<deque> is a double-ended queue, that means one can
insert and delete elements from both ends, it is a kind of
combination between a stack (last in first out) and a queue
(first in first out) and constitutes a compromise between a
<vector> and a <list>. the iterator used is bidirectional.

Associative Containers
In an associative container the items are not arranged in
sequence, but usually as a tree structure or a hash table.
The main advantage of associative containers is the speed
of searching (binary search like in a dictionary)
Searching is done using a key which is usually a single
value like a number or string
The value is an attribute of the objects in the container
The STL contains two basic associative containers
sets and multisets
maps and multimaps

Associative Containers
A <set> stores a number of items which contain keys. The keys are
the attributes used to order the items, for example a set might store
objects of the class Person which are ordered alphabetically using
their name
A <map> stores pairs of objects: a key object and an associated
value object. A <map> is somehow similar to an array except
instead of accessing its elements with index numbers, you access
them with indices of an arbitrary type.
<set> and <map> only allow one key of each value, whereas
<multiset> and <multimap> allow multiple identical key values

Derived Containers
STL provides three derived containers namely,
Stack
queue
priority_queue

these containers are derived from different


sequence containers. These are also known as
container adaptors.
the derived containers doesn't support iterators &
therefore we cannot use them for data
manipulation.
but they support two member functions push() and
pop() for implementing insert & delete operations.

Algorithms
Algorithms are defined as the step by step process for
mnaipulating functions.
STL algorithms allows us to work with two different
types of containers at the same time.
STL algorithms are not member functions or friends of
containers. they are standalone template functions.
STL algoritms, provides more than sixty algorithms
which are used to support complex operations. They are
retrive or non-mutating algorithms- find(), search()

mutating algorithms- copy(), replace()


sorting algorithms- sort(), merge()
set algorithms
relational algorithms

Iterators
Iterators are pointer-like entities that are used to access individual
elements in a container.
Often they are used to move sequentially from element to element,
a process called iterating through a container.
vector<int>
array_

17

vector<int>::iterator

4
23
12
size_

The iterator corresponding to


the class vector<int> is of
the type vector<int>::iterator

Iterators
The member functions begin() and end() return an
iterator to the first and past the last element of a container
vector<int> v
array_

17

v.begin()

4
23
12
size_

v.end()

Iterators
One can have multiple iterators pointing to different or identical
elements in the container
vector<int> v
array_

17
4
23

i1
i2

12
size_

i3

Iterator Categories
Not every iterator can be used with every container for
example the list class provides no random access iterator
Iterators are divided into five categories in which a higher
(more specific) category always subsides a lower (more
general) category, e.g. An algorithm that accepts a forward
iterator will also work with a bidirectional iterator and a
random access iterator .

input
forward
output

bidirectional

random
access

The input and output support the least functions.


They can be used only to traverse in a container.
The forward iterator supports all operations of
input and output iterators and also retains its
position in the container.
A bidirectional iterator supporting all forward
iterator operations provides the ability to move
in the backward direction in the container.
A random access container combines the
functionality of a bidirectional iterator with an
ability to jump to an arbitary location.

Anda mungkin juga menyukai