Wednesday, March 28, 2018

Write a C++ program to illustrate map and map operations.


AIM: Write a C++ program to illustrate map and map operations.

THEORY:
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values
Functions associated with Map:
begin() – Returns an iterator to the first element in the map
end() – Returns an iterator to the theoretical element that follows last element in the map
size() – Returns the number of elements in the map
max_size() – Returns the maximum number of elements that the map can hold
empty() – Returns whether the map is empty
pair insert(keyvalue,mapvalue) – Adds a new element to the map
erase(iterator position) – Removes the element at the position pointed by the iterator
erase(const g)- Removes the key value ‘g’ from the map
clear() – Removes all the elements from the map
key_comp() / value_comp() – Returns the object that determines how the elements in the map are ordered (‘<' by default)
find(const g) – Returns an iterator to the element with key value ‘g’ in the map if found, else returns the iterator to end
count(const g) – Returns the number of matches to element with key value ‘g’ in the map
lower_bound(const g) – Returns an iterator to the first element that is equivalent to mapped value with key value ‘g’ or definitely will not go before the element with key value ‘g’ in the map
upper_bound(const g) – Returns an iterator to the first element that is equivalent to mapped value with key value ‘g’ or definitely will go after the element with key value ‘g’ in the map

 
SOURCE CODE:
#include<iostream>
#include<map>
#include<string>
using namespace std;
typedef map<string,int>item_map;
int main()
{
            int sz;
            string item_name;
            int code_no;
            item_map item;
            for(int i=0;i<2;i++)
            {
                        cout<<"\n Enter item name";
                        cin>>item_name;
                        cout<<"\n Enter code number:";
                        cin>>code_no;
                        item[item_name]=code_no;
            }
            item["PC"]=2510;
            item.insert(pair<string,int>("printer",211));
            sz=item.size();
            cout<<"\n size of map"<<sz<<"int n";
            cout<<"\n list of item name and code:";
            item_map::iterator t;
            for(t=item.begin();t!=item.end();t++)
            {
                        cout<<(*t).first<<" "<<(*t).second<<"\n";
                        cout<<"\n";
            }
            cout<<"\n ENter item name";
            cin>>item_name;
            code_no=item[item_name];
            cout<<"\n code_no:"<<code_no<<"\n";
            return 0;
}

Labels:

Write a C++ program to implement deque and deque operations.


AIM: Write a C++ program to implement deque and deque operations.
THEORY:
Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed.
The functions for deque are same as vector, with an addition of push and pop operations for both front and back.

SOURCE CODE:
#include<iostream>
#include<deque>
#include<string>
#include<stdlib.h>
using namespace std;
int main(){
            deque<int>dq;
            deque<int>::iterator it;
            int choice,item;
            while(1){
                        cout<<"\n ...."<<endl;
                        cout<<"\n deque implementation is stl"<<endl;
                        cout<<"\n ....."<<endl;
                        cout<<"\n 1.Insert element in the end"<<endl;
                        cout<<"\n 2.Insert element at front"<<endl;
                        cout<<"\n 3,Delete element at the end"<<endl;
                        cout<<"\n 4.Delete element at the front"<<endl;
                        cout<<"\n 5.Front element at deque"<<endl;
                        cout<<"\n 6.Least element at deque"<<endl;
                        cout<<"\n sieof deque"<<endl;
                        cout<<"\n 8.Display deque"<<endl;
                        cout<<"\n 9.Exit"<<endl;
                        cout<<"enter your choice"<<endl;
                        cin>>choice;
                        switch(choice) {
                                    case 1:cout<<"\n Enter value to be inserted at the end";
                                          cin>>item;
                                          dq.push_back(item);
                                          break;
                                    case 2:cout<<"\n Enter value to be inserted at the front" ;
                                           cin>>item;
                                                   dq.push_front(item);
                                                   break;
                                    case 3:item=dq.back();
                                           dq.pop_front();
                                                   cout<<"\n Element"<<item<<"deleted"<<endl;
                                                   break;
                                    case 4:item=dq.front();
                                            dq.pop_front();
                                                    cout<<"\n element"<<item<<"deleted"<<endl;
                                                            break;
                            case 5:cout<<"\n Front elements of the deque";
                                          cout<<dq.front()<<endl;
                                                  break;
                        case 6:cout<<"\n Back elements of the deque";
                                          cout<<dq.back()<<endl;
                                                  break;
                        case 7:cout<<"\n size of the deque"<<dq.size()<<endl;
                                           break;
                        case 8:cout<<"\n Element of the deque";
                                           for(it=dq.begin();it!=dq.end();it++)
                                                   {
                                                            cout<<*it<<" ";
                                                            cout<<endl;
                                                            break;
                                                    }       
                        case 9:exit(1);
                                           break;
                                    default:"wrong choice";                                                                                                                   
                        }
            }
}

Labels:

Write a C++ program to illustrate vector and vector operations.


AIM: Write a C++ program to illustrate vector  and vector operations.
THEORY:
Vectors are sequence containers representing arrays that can change in size.

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.

Instead, vector containers may allocate some extra storage to accommodate for possible growth, and thus the container may have an actual 
capacity greater than the storage strictly needed to contain its elements (i.e., its size). Libraries can implement different strategies for growth to balance between memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing intervals of size so that the insertion of individual elements at the end of the vector can be provided with amortized constant time complexity (see push_back).

Therefore, compared to arrays, vectors consume more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.

Compared to the other dynamic sequence containers (
dequeslists and forward_lists), vectors are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements from its end. For operations that involve inserting or removing elements at positions other than the end, they perform worse than the others, and have less consistent iterators and references than lists and forward_lists.
SOURCE CODE:
#include<iostream>
#include<vector>
using namespace std;
int main(){
            vector<int>e;
            e.push_back(5);
            e.push_back(8);
            e.push_back(9);
            cout<<"\n the elements are";
            cout<<e[0]<<endl;
            cout<<e[1]<<endl;
            cout<<"\n elements in ascending order";
            for(int x=0;x<8;x++){
                        e.push_back(x+1);
                        cout<<x+1<<endl;
            }
            int s=e.size()-1;
            cout<<"\n elements in descending order";
            for(int j=s;j>=3;j--){
                        cout<<e[j]<<endl;
            }
            return 0;
}

Labels:

Write a C++ program to illustrate list and list operations


AIM: Write a C++ program to illustrate list and list operations
THEORY:
List
Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions.

List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they contain in different and unrelated storage locations. The ordering is kept internally by the association to each element of a link to the element preceding it and a link to the element following it.

They are very similar to forward_list: The main difference being that forward_list objects are single-linked lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient.

Compared to other base standard sequence containers (
arrayvector and deque), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

The main drawback of lists and forward_lists compared to these other sequence containers is that they lack direct access to the elements by their position; For example, to access the sixth element in a list, one has to iterate from a known position (like the beginning or the end) to that position, which takes linear time in the distance between these. They also consume some extra memory to keep the linking information associated to each element (which may be an important factor for large lists of small-sized elements).

SOURCE CODE:
#include<iostream>
#include<list>
using namespace std;
void show(list<int>&num)
{
            list<int>::iterator n;
            for(n=num.begin();n!=num.end();++n)          
{
                        cout<<*n<<"";
            }
}
int main()
{
            list<int>list;
            list.push_back(5);
            list.push_back(10);
            list.push_back(15);
            list.push_back(20);
            cout<<"\n number are:-";
            show(list);
            cout<<"\n interest elements at the begining of list";
            list.push_front(25);
            cout<<"\n after inserting elements are:";
            show(list);
            cout<<"\n delete elements at the begining";
            list.pop_front();
            cout<<"\n delete least elements";
            list.pop_back();
            cout<<"\n after deleting numbers are:";
            show(list);
            cout<<"\n elements in reverse order:";
            list.reverse();
            show(list);
            return 0;
}

Labels:

Write a Program to rethrow an Exception


AIM: Write a Program to rethrow an Exception
Theory:
If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression (throwwithout assignment_expression) causes the originally thrown object to be rethrown.

Because the exception has already been caught at the scope in which the rethrow expression occurs, it is rethrown out to the next dynamically enclosing try block. Therefore, it cannot be handled by catch blocks at the scope in which the rethrow expression occurred. Any catch blocks for the dynamically enclosing try block have an opportunity to catch the exception.

Program:
#include<iostream>
using namespace std;
void sub(int i,int j)
{
            try
            {
                        if(i==0)
                        {
                                    throw i;
                        }
                        else
                        cout<<"Subtraction result is "<<i-j<<endl;
            }
            catch(int i)
            {
                        cout<<"Exception caught inside sub()\n";
                        throw;
            }
};
int main()
{
            try
            {
                        sub(8,4);
                        sub(0,8);
            }
            catch(int k)
            {
                        cout<<"Exception caught inside main()\n";
            }
            return 0;
}


Labels:

Write a C++ program for Exception Handling Divide by zero.


AIM: Write a C++ program for Exception Handling Divide by zero.
THEORY:
Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution. It is provided by specialized programming language constructs, computer hardware mechanisms like interrupts or operating system IPC facilities like signals.
In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler. The details of how this is done depends on whether it is a hardware or software exception and how the software exception is implemented. Some exceptions, especially hardware ones, may be handled so gracefully that execution can resume where it was interrupted.
Alternative approaches to exception handling in software are error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values or some auxiliary global variable such as C's errno or floating point status flags; or input validation to preemptively filter exceptional cases.

SOURCE CODE:
#include<iostream>
using namespace std;
int main()
{
            int a,b,c;
            float d;
            cout<<"\n Enter value of a:";
            cin>>a;
            cout<<"\n Enter value of b:";
            cin>>b;
            cout<<"\n Enter value of c:";
            cin>>c;
            try
            {
                        if((a-b)!=0)
                        {
                                    d=c/(a-b);
                                    cout<<"\n Result is"<<d;
                        }
                        else
                        {
                                    throw (a-b);
                        }
            }
            catch (int i)
            {
                        cout<<"Ans is infinte because a-b is"<<i;
            }
            return 0;
}

Labels:

Write a c++ program to illustrate member function template.


AIM: Write a c++ program to illustrate member function template.

THEORY:
In Function Templates, a function template was defined outside of any template class. However, functions in C++ are often member functions of a class. If you want to create a class template and a set of function templates to go with that class template, you do not have to create the function templates explicitly, as long as the function definitions are contained within the class template. Any member function (inlined or noninlined) declared within a class template is implicitly a function template. When a template class is declared, it implicitly generates template functions for each function defined in the class template.
You can define template member functions three ways:
  1. Explicitly at file scope for each type used to instantiate the template class.
  2. At file scope with the template arguments.
  3. Inlined in the class template itself.
Member function templates are used to instantiate any functions that are not explicitly generated. If you have both a member function template and an explicit definition, the explicit definition is used.
The template argument is not used in a constructor name. For example: 
template<class L> class Key
{
      Key();            // default constructor
      Key( L );         // constructor taking L by value
      Key<L>( L );      // error, <L> implicit within class template
};
The declaration Key<L>(L) is an error because the constructor does not use the template argument. Assuming this class template was corrected by removing the offending line, you can define a function template for the class template's constructor: 
// Constructor contained in function template:
template<class L>
      Key<L>::Key(int) { /* ... */ }
      // valid, constructor template argument assumed template<class L>

      Key<L>::Key<L>(int) { /* ... */ }
      /* error, constructor template argument <L> implicit
         in class template argument */
A template function name does not include the template argument. The template argument does, however, appear in the template class name if a member function of a template class is defined or declared outside of the class template.

The definition:
Key<L>::Key(int)
 {
 /* ... */
} is valid because Key<L> (with template argument) refers to the class, while Key(int) { /* ... */ } refers to the member function.

SOURCE  CODE:
#include<iostream>
using namespace std;
template<class E>
void exchange (E&a,E&b)
{
            E temp=a;
            a=b;
            b=temp;
};
int main()
{
            int x=5,y=8;
            float a,b;
            cin>>a>>b;              
            cout<<"\n enter the values:";
            cout<<"\n before exchange"<<"\n x="<<x<<"\n y="<<y;
            exchange(x,y);
            cout<<"\n after exchange"<<"\n x="<<x<<"\n y="<<y;
            cout<<"\n before exchange"<<"\n a="<<a<<"\n b="<<b;
            exchange(a,b);
            cout<<"\n after exchanging"<<"\n a="<<a<<"\n b="<<b;
            return 0;
}

Labels: