Showing posts with label CPP Notes. Show all posts
Showing posts with label CPP Notes. Show all posts

Saturday, February 2, 2013

STL (Standard Template Library) of C++


STL (Standard Template Library):
STL provide a readymade set of common classes for C++. The STL is general purpose classes (Data Structure) and function (Algorithm) that could be used as a standard approach for storing data and processing of data.

Components of STL –
1.     Containers:
A container is an object that store data. It is a way by which data is organised in memory. The STL containers are implemented by template class and therefore can be easily customized.
2.     Algorithms:
An algorithm is a procedure that is used to process the data contained in the container. The STL includes many different kind of algorithm to provide support to tasks such as initializing, searching, copying, sorting and merging. Algorithms are implemented by template function.
3.     Iterators:
An iterator is an object that point to an element in a container. We can use iterator to move through the contents of the container. Iterator can handle the data of container. Iterator connect algorithm with container.


Application of container class –
                                                        i.            Stack
                                                      ii.            Queue
                                                    iii.            Vector
                                                   iv.            DeQue
                                                     v.            List
                                                   vi.            Map
                                                 vii.            Multimap
                                               viii.            Priority_Queue

File Handling in C++


File Handling:
Header file used for file handling is fstream.h.
·        It is a process of storing data into files.
·        File handling transfers data between program and hard disk file.
·        C++ has its own function to access file data and store data into files.






Simple program:
void main()
{
            char *name; int roll_no;
            ofstream fout(“data”);
            fout<<”Rahul”;
            fout<<101;
            fout.close();
            ifstream fin(“data”);
            fin>>name;
            fin>>roll_no;
            cout<<roll_no<<name;
            fin.close();
}







File Modes:
File modes specify that, how file data will be read and write operation perform.

Mode
Description
1.
ios::in
Open file for read only mode.
2.
ios::out
Open file for writing mode.
3.
ios::app
Append data to the end of file.
4.
ios::ate
Write data on the end of file and provide the facility of modifying existing contents.
5.
ios::binary
Create the binary file.
6.
ios::nocreate
Open fail if file does not exist.
7.
ios::noreplace
Open fail if file already exist.
8.
ios::trunc
Delete all the contents of the file if it exists. It will not create new file.

Note: The mode can combine two or more parameter using the bitwise OR (|).

Input and Output Functions for File handling:
·        Put and Get function:
                                i.            Put function:
The put function writes a single character to the associated stream/file.
For Ex:
file.put(c)
Writes a character c to the output buffer at the current put position and increases the put pointer to point the next character.

                              ii.            Get function:
The get function read a single character from the associated stream/file.
For Ex:
file.get(c)
Reads a character c from the current position and increment get pointer to the next character for next data get.
Sample program for file handling:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
            fstream file;
            file.open(“data.txt”,ios::in|ios::out);
            char c[4]={‘a’,’b’,’c’,’d’}, data;
            for(int i=0;c[i]!=NULL;i++)
            {
                        file.put(c[i]);
            }
            file.seekg(0);
            cout<<”\n Reading data from file\n”;
            while(file)
            {
                        file.get(data);
                        cout<<data;
            }
            file.close();
}
·        Write and read function:
Write and read functions are specially designed to input or output binary data in sequence.
file.read((char *)&v, sizeof(v));
file.write((char *)&v,sizeof(v));
file.read(memory_block,size);
file.write(memory_block,size);

Function for manipulating file pointer:
C++ provides some functions that relocate the file pointer and we can set any position inside the file.

                    i.            seekg():
Move get pointer to specific location.

                  ii.            seekp():
Move put pointer to specific location.

                iii.            tellg():
Give the current position of get pointer.

               iv.            tellp():
Give the current position of put pointer.

Reference Positions
0
ios::beg
1
ios::cur
2
ios::end
Examples:                                                                                          
file.tellp();
file.seekg(offset,reference position);
file.seekg(0);




Error handling in file operation:
Error that may occur –
                    i.            A file which we are trying to open for reading does not exist.
                  ii.            The file name used for a new file may already exist.
                iii.            We may use an invalid file name.
               iv.            There may not any space in the disk for storing more data.
Error handling functions for file handling –
        i.            eof():
Return true, if end of file (EOF) is detected while reading a file. Otherwise returns false.
      ii.            bad():
Return true, if an invalid operation has occurred, otherwise false.
    iii.            good():
Return true, if no error has occurred, otherwise return fail.
   iv.            fail():
Return true, when an input or output operation has failed.

Exception Handling in C++


Exception Handling:
Those errors comes in program at run time is known as exception. To manage these exceptions we create procedure, this is known as exception handling.

Advantages of exception handling:
                                                        i.            We can trace the error.
                                                      ii.            It makes error free program.
                                                    iii.            Exception handling helps to detect program run time error.

Note:  This feature of  C++ is not supported in Borland Trubo C++

Try Block:
The keyword try contains the block of statements surrounded by braces, which may generated and this block of statement is known try block.

Catch Block:
This block catch the exception (handle) generated in try block, it is thrown in the catch block.

Throw statement:
When exception is detected, the throw statement sends the control to catch block.
(The throw statement exists in try block. When throw statement execute, it pass control to catch block.)






#include <iostream.h>
#include<conio.h>
class Error
{
            public:
            void devide(int x, int y)
            {
                        If(y!=0)
                        {
                                    int Result;
                                    Result=x/y;
                                    cout<<”Result ”<<Result;
                        }
                        else
                        {
                                    throw(y);
                        }
            }
};




void main()
{
            try
            {
                        Error e1;
                        e1.divide(10,0);
            }
            catch(int errr)
            {
                        cout<<”Ececution ”<<err;
            }
}

Specifying Exception:
Specifying Exception and multiple catch blocks:
It is possible to restrict a function to throw only specific exceptions. This is done by specific throw list to function definition.

Note:- If throw statement do not have any list then this function do not throw any exception.
void test(int x) throw(int, double)
{
if(x==0)
            throw ‘x’;
else if(x==1)
            throw 1;
else if(x==-1)
            throw 1.5;
}
void main()
{
            Try
{
            cout<<”Test throw statement”;
            test(0);
            test(1);
            test(-1);
}
catch(int i)
{
            cout<<”Integer exception”;
}
catch(char i)
{
            cout<<”Character exception”;
}
catch(double i)
{
            cout<<”Double exception”;
}
}

Rethrow Exception:
When a throw exception generate an exception and transfer the control to outer try catch block.
void divide(int x,int y)
{
            try
            {
                        if(y==0)
                        {
            throw(y);
}
else
{
            cout<<”Division : ”x/y;
}
}
catch(int)
{
            throw;
}
}
void main()
{
try
            {
divide(10,2);
divide(20,0);
}
catch(int)
{
            cout<<”Exception generate”;
}
cout<<”End of try catch”;
}

Template Class in C++


Template Class:

template <class T1, class T2>
class test
{
 T1 a;
 T2 b;
 public:
 test(T1 x , T2 y)
 {
  a=x;
  b=y;
 }
 void show()
 {
  cout<<a<<”and”<<b;
 }
};

void  main()
{
 test< float , int > test1 (1.30,123);
 test<int , char> test2 (10,’w’);
 test1.show();
 test2.show();
getch();
}

A class created from class template is called a template class.

Syntax:
class_name < type > object_name(argument list);

Powered by Blogger.