0% found this document useful (0 votes)
10 views

C++ - Unit V

C++

Uploaded by

Janu Prakash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

C++ - Unit V

C++

Uploaded by

Janu Prakash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Template

TEMPLATES AND STL


Class templates: Implementing a class template - Implementing class template member functions –
Using a class template – Function templates – Implementing function templates – Using template
functions – Template instantiation – Class template specialization – Template class partial
specialization – Template function specialization – Template parameters – Static members and
variables – Templates and friends – Templates and multiple – File projects. Standard Template
library: Containers – Iterators and application of container classes.

PART A:

1. What is a template?

Templates support generic programming, which allows to develop reusable software


components such as functions, classes etc., supporting different data types in a single framework.

2. What is class template?

Classes can also be declared to operate on different data types. Such classes are called class
templates. A class template specifies how individual classes can be constructed similar to normal class
specification

3. Write The Syntax Of Class Template

template <class T1, class T2…>

Class classname

T1 data1;

….

//functions of template arguments T1, T2…

Void func1 (T1 a, T2 &b);

T func2 (T2 *x, T2 *y);

1
};

4. What is function template? [aug2011]

A function template specifies how an individual function can be constructed. The


limitation of such functions is that they operate only on a particular data type. It can be overcome by
defining that function as a function template or generic function.

5. Write The Syntax Of Function Template

template<class T…>

ReturnType FuncName (arguments)

…..//body of the function template

…..

6. Different between function template and template function?

Function template
Is a template used to generate template functions? A function template can be only a
declaration, or it can define the function.
Template function
Is a function generated by a function template?

7. Different between class template and template class? [aug 2010]

Class template

Is a template used to generate template classes? A class template can be only a declaration, or
it can be a definition of the class.

Template class

Is an instance of a class template?

8. What is RTTI?

Run-time type information (RTTI) is a mechanism that allows the type of an object to be
determined during program execution.

9. List out RTTI?

2
a) Base Type

b) Compound Type

c) Container Type

10.Explain the other functions of RTTI.

i) Insert elements into the container

ii) Delete elements of the container

iii) Iterate through the elements of the container

11. Explain the three parts of rtti system

1) RTTI description of Base Types

2) Property Description of compound and container types

3) Property iterators.

12. Define RTTI?

Run Time Type Information, a facility that allows an object to be queried at runtime to determine
its type. One of the fundamental principles of object technology is polymorphism, which is the ability
of an object to dynamically change at runtime

13. What are the issues related with RTTI?

Some of the RTTI related issues are follows:

 Backward compatibility with C and Casting


 Efficiency
 Using virtual functions in place of RTTI

14. What is real time type information (RTTI)?

Real times Information is a mechanism by which we can find the type of an object are run
time.

15. What are the operators provided by RTTI?

RTTI is provided through two operators:

The typeid operator

The dynamic cast operator

3
16. Why do we need RTTI?

RTTI can be used to find out the type of the polymorphic object at runtime. RTTI can be used
to fine out the type of the element in the body of a template function or class.

17. List The Different Type Of Casting Operators

 Reinterpret cast
 Dynamic cast
 Static cast
 Const_cast

18. What is mean by class template?

A class template provides a specification for generating classes based on parameters. For
example, the C++ standard library has a list container called list, which is a template. The statement
list<int> designates or instantiates a linked-list of type int. The statement list<string> designates or
instantiates a linked-list of type string.

Just as we can define function templates, we can also define class templates. The general form of a
generic class declaration is shown here:

template <class type> class class-name {


.
.
.
}

Here, type is the placeholder type name, which will be specified when a class is instantiated. You can
define more than one generic data type by using a comma-separated list.

19. List down the advantages of class templates [aug2011]

 One C++ Class Template can handle different types of parameters.


 Compiler generates classes for only the used types. If the template is instantiated for int type,
compiler generates only an int version for the c++ template class.
 Templates reduce the effort on coding for different data types to a single set of code.
 Testing and debugging efforts are reduced

20. Define parameterizing?

Another way to say, "Class templates." A parameterized type is a type that is parameterized over
another type or some value. List<int> is a type (List) parameterized over another type (int).

4
Parameterized Class

21. What is standard template library?

The collection of these generic classes and functions is called the Standard Template Library

22. List The Components Of Stl

The STL contains several components. They are

1) Container

2) Algorithm

3) Iterators.

23. What is an algorithm?

An algorithm is a procedure that is used to process the data contained in the containers. The
STL includes many different kinds of algorithms to provide support to tasks such as initializing,
searching, copying, and sorting and merging

24. State The Advantages Of Using Generic Algorithm

 They are readymade from STL


 They are efficient
 They are standard
 Easy to learn

25. What is mean by function adaptor? [aug 2011]

 A function adaptor is an instance of a class that adapts a namespace-scope or member


function so that the function can be used as a function object. A function adaptor may also
be used to alter the behavior of a function or function object.

5
 Each function adaptor defined by the C++ Standard Library provides a constructor that
takes a namespace-scope or member function. The adaptor also defines a function call
operator that forwards its call to that associated global or member function.

PART B

1. What is mean by template class? [aug 2010]

TEMPLATE CLASS:

Templates allow us to define generic classes using templates with an anonymous type

SYNTAX:

Template<class T>

Class classname

//----

};

A template definition is identical to any valid class definition that the template might generate,
except for the following:

The class template definition is preceded by

Template< template-parameter-list >

Where template-parameter-list is a comma-separated list of one or more of the following kinds of


template parameters:

 Type
 non-type
 template
 Types, variables, constants and objects within the class template can be declared using the
template parameters as well as explicit types (for example, int or char).

A class template can be declared without being defined by using an elaborated type specifier. For
example:

Template<class L, class T> class Key;

6
This reserves the name as a class template name. All template declarations for a class template must
have the same types and number of template arguments. Only one template declaration containing
the class definition is allowed.

Note:

When you have nested template argument lists, you must have a separating space between the > at
the end of the inner list and the > at the end of the outer list. Otherwise, there is an ambiguity
between the extraction operator >> and two template list delimiters >.

Template<class L, class T> class Key {/* ... */};

Template<class L> class Vector {/* ... */};

Int main ()

Class Key <int, Vector<int> > my_key_vector;

// implicitly instantiates template

Objects and function members of individual template classes can be accessed by any of the
techniques used to access ordinary class member objects and functions. Given a class template:

Template<class T> class Vehicle

Public:

Vehicle () {/* ... */} // constructor

~Vehicle () {}; // destructor

T kind [16];

T* drive ();

Static void roadmap ();

// ...

};

And the declaration:

Vehicle<char> bicycle; // instantiates the template

7
EX:

#include<iostream.h>
Const size=3;
Template<class T>
Class vector
{
T* V;
Public:
Vector ()
{
V=new T[size];
For (int i=00; i<size; i++)
V[i] =0;
}
Vector (T*a)
{
For (int i=0; i<size; i++)
V[i] =a[i];
}
T operator *(vector & y)
{
T sum=0;
For (int i=0; i<size; i++)
Sum +=this->v[i]*y.v[i];
Return sum;
}
};
Int main ()
{
Int X [3] = {1, 2, 3};
Int Y [3] = {4, 5, 6};
Vector<int>V1;
Vector<int>V2;
V1=x;
V2=Y;
Int R=v1 *v2;
Cout<<”R=”<<R<<”\n”;
Return 0;
}
O/P:
R=32

8
CLASS TEMPLATES WITH MULTIPLE PARAMETERS:
Syntax:
Template<class T1, class T2....>
Class classname
{
------
};
Example:
#include<iostream.h>
Template<class T1, class T2>
Class test
{
T1 a;
T2 b;
Public:
Test (T1 Z, T2 Y)
{
a=X;
b=Y;
}
Void show ()
{
Cout<<a<<”and”<<b<<”\n”;
};
Int main ()
Test<float, int>test1 (1.23, 123);
Test<int, char>test2 (100, w’);
Text1.show ();
Text 2.show ();
Return 0;
}
2. Define function template with suitable example? [Aug 2011]
GENERIC FUNCTION:

A generic function defines a general set of operations that will be applied to various types of
data
The type of data that the function will operate upon is passed to it as parameter
A generic function created by using the keyword template.
It contain two types
1. Function template
2. Class template
FUNCTION TEMPLATE:

9
Function template that could be used to create a family with different argument types.
SYNTAX:
Template<class T>
Return type function name (argument of types)
{
//.....
//body of function
}
EX:
#include<iostream.h>
Template<class T>
Void swap (T &x, T&y)
{
T temp=x;
X=y;
Y=temp;
}
Void fun (int m, int n, float a, float b)
{
Cout<<”m and n before swap”<<m<<””<<n<<”\n”;
Swap (m, n);
Cout<<”m and n after swap”<<m<<” “<<n<<”\n”;
Cout<<”a and b before swap”<<a<<” “<<b<<”\n”;
Swap (a, b);
Cout<<”a and b after swap”<<a<<” “<<b<<”\n”;
}
Int main ()
{
Fun (100, 200, 11, 22, 33, 44);
Return 0;
}
O//P:
M and n before swap: 100 200
M and n after swap: 200 100
A and b before swap: 11.22 33.43
A and b after swap: 33.43 11.22
BUBBLE SORT USING TEMPLATE FUNCTION:
#include<iostream.h>
Template<class T>
Void bubble (T a [], int n)
{
For (int i=0; i<n-1; i++)

10
For (int j=n-1; i<j; j--)
If (a[j] <a [j-1])
{
Swap (a[j], a [j-1]);
}
}
Template<class x>
Void swap(x &a, x&b)
{
X temp=a;
A=b;
B=temp;
}
Int main ()
{
Int X [5] = {10, 50, 30, 40, 20};
Float y [5] = {1.1, 5.5, 3.3, 4.4, 2.2}
Bubble(x, 5);
Bubble(y, 5);
Cout<<”sworted x array”;
For (int i=0; i<5; i++)
Cout<<x[i] <<” “;
Cout<<endl;
Cout<<”sorted y array”;
For (int j=0; j<5; j++)
Cout<<y[j] <<” “;
Cout<<endl;
Return 0;
}
O/P:
Sorted x array: 10 20 30 40 50
Sorted y array: 1.1 2.2 3.3 4.4 5.5
FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS:
A function templates contains more than one parameter is called multiple parameters.
SYN:
Template<class T, class T2,>
Return type function name (argument of types T1, T2)
- - - -
- - - -
- - - -
Body of function
-- - -

11
}
EX:
#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;
}
3. WRITE A TEMPLATE FUNCTION TO FIND THE MINIMUM AND MAXIMUM VALUE IN AN
ARRAY? [Aug 2010]
#include <iostream>
using std::Cout;
using std::endl;

template<class T> T max(const T* data, int size) {


T result = data[0];
for(int i = 1 ; i < size ; i++)
if(result < data[i])
result = data[i];
return result;
}

template<class T> T min(const T* data, int size) {


T result = data[0];
for(int i = 1 ; i < size ; i++)
if(result > data[i])
result = data[i];
return result;
}

int main() {
double data[] = {1.5, 4.6, 3.1, 1.1, 3.8, 2.1};
int numbers[] = {2, 22, 4, 6, 122, 12, 1, 45};

const int dataSize = sizeof data/sizeof data[0];


Cout << "Minimum double is " << min(data, dataSize) << endl;
Cout << "Maximum double is " << max(data, dataSize) << endl;

const int numbersSize = sizeof numbers/sizeof numbers[0];


cout << "Minimum integer is " << min(numbers, numbersSize) << endl;

12
cout << "Maximum integer is " << max(numbers, numbersSize) << endl;

return 0;
}
Minimum double is 1.1
Maximum double is 4.6
Minimum integer is 1
Maximum integer is 122

4. WHAT IS MEANT BY RTTI? STATE THE NEED FOR RTTI. STATE THE DIFFERENT TYPES
OF CASTING. STATE THE ISSUES OF RTTI.

RTTI:

Definition

“Run Time Type Information is a mechanism to decide the type of the object at runtime”.

 Most of the compilers provide RTTI but disable it by default. It adds overhead at run time.
 RTTI also impacts the performance of the system to a notable extent.
ANSI C++ standardization committee has added two keywords to work with RTTI:

1. Typeid: It is an operator that returns the type of object in a specific form (the type
info object).
2. Dynamic_cast: This is a new casting operator provided in C++ which casts a
polymorphic object into another.
Need for RTTI:

 RTTI can be used to find out the type of the polymorphic object at run time.
 RTTI can be used to find out the type of the element in the body of a template function or
class.
Casting operator:

A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator.

The most general cast supported by most of the C++ compilers is as follows:

(Type) expression

13
Different types of casting:

1. Reinterpret-cast:

The reinterpret cast operator changes a pointer to any other type of pointer. It also allows
casting from pointer to an integer type and vice versa. A casting operator for abnormal casting cases
like int to pointer and pointer to int etc.

2. Const_cast:

The const_cast operator is used to explicitly override const and/or volatile in a cast. The target
type must be the same as the source type except for the alteration of its const or volatile attributes.
This type of casting manipulates the const attribute of the past object, either to be set or removed.
This C++ operator casts a contextual const pointer to a non-const variable pointer.

3. Static cast:

The static cast operator performs a nonpolymorphic cast. For example, it can be used to cast a
base class pointer into a derived class pointer. A casting operator for normal casting cases like int to
float and char to int etc.

4. Dynamic-cast:

The dynamic cast performs a runtime cast that verifies the validity of the cast. If the cast
cannot be made, the cast fails and the expression evaluates to null. A dynamic cast performs casts on
polymorphic types and can cast an A* pointer into a B* pointer only if the object being pointed to
actually is a B object. Casting operator that can be used to safeguard against irrelevant casting.

Issues of RTTI:

 Backward compatibility with C and Casting


 RTTI is not efficient. Runs slower.
 Need to use virtual functions for more efficiency

5. EXPLAIN THE CONCEPTS OF RTTI AND TEMPLATES

RTTI AND TEMPLATES:

14
RTTI can be used to find out the type used by the template. The type is determined at compile time.
Both typeid and dynamic cast can be used for performing validations

1. Using Typeid for Template objects:

Program:

#include<iostream.h>
#include<conio.h>
Using namespace std;
Template<typename T1, typename T2>
Class JustForSearch
{
Public:
Void Search (T1 Array [ ], T2 UserInput)
{
Bool b=false;
If (typeid (User Input) = =typed (T1)) //Validations
{
For (int i=0; i<3; i++)
{
If (Array[i] = =UserInput)
b=true;
}
If (b)
Cout<<”Found”;
Else
Cout<<”Not found”;
}
Else
{
Cout<<”Element to be Searched is not correct:
}
}
};

15
Void main ( )
{
Int Array [ ] = {10, 20, 30};
Int ElementToBeSearched1;
Cout<<”\nEnter the element to be Searched in the array….”
Cin>> ElementToBeSearched1;
JustForSearch<int, int>JS;
JS.Search (Array, ElementToBeSearched1);
//integer array, integer searching element
Char ElementToBeSearched2;
Cout<<”\nEnter the element to be Searched in the array….”
Cin>> ElementToBeSearched2;
JustForSearch<int, char>JS1;
JS1.Search (Array, ElementToBeSearched2);
//integer array, character searching element
}
Sample Output
Enter the element to be searched in the array………30
Found
Enter the element to be searched in the array………a
Element to be searched is not correct

2. Using dynamic cast for Template objects:


Program:

#include<iostream.h>
#include<conio.h>
Using namespace std;
Template<typenmae Type>
Class One
{
Public:
Type on;
One (Type t)
{

16
On=t;
}
Virtual void show ( ) {Cout<<on ;}
};
Template<typenmae Type>
Class Two: public One<Type>
{
Public:
Type t1, t2;
Two (Type temp, Type to): One<int> (temp)
{
t1=to;
t2=temp;
}
Void show ( ) {Cout<<t1<<t2 ;}
};
Void main ( )
{

One<int> O (12);

One<int>*PtrOne;

PtrOne=dynamic cast<One<int>*> (&O); //casting

PtrOne->Show ( );

Two<int>T (10, 20);

PtrOne=dynamic cast<One<int>*> (&T); //casting

PtrOne->Show ( );

Sample Output

12 20 10

6. What is mean by class template with suitable example? [Aug 2010]

Just as we can define function templates, we can also define class templates. The general form
of a generic class declaration is shown here:

Template <class type> class class-name {


.
.
.
}

17
Here, type is the placeholder type name, which will be specified when a class is instantiated. You can
define more than one generic data type by using a comma-separated list.

Following is the example to define class Stack<> and implement generic methods to push and pop
the elements from the stack:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

Using namespace std;

Template <class T>


Class Stack {
Private:
Vector<T> elems; // elements

Public:
Void push (T const&); // push element
Void pop (); // pop element
T top () const; // return top element
Bool empty () const { // return true if empty.
Return elems.empty ();
}
};

Template <class T>


Void Stack<T>: push (T const& elem)
{
// append copy of passed element
elems.push_back (elem);
}

Template <class T>


Void Stack<T>:: pop ()
{
If (elems.empty ()) {
Throw out_of_range ("Stack<>::pop (): empty stack");
}
// remove last element
elems.pop_back ();
}

Template <class T>


T Stack<T>:: top () const
{

18
If (elems.empty ()) {
Throw out_of_range ("Stack<>:: top (): empty stack");
}
// return copy of last element
Return elems. Back ();
}

Int main ()
{
Try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings

// manipulate int stack


intStack.push (7);
Cout << intStack. Top () <<endl;

// manipulate string stack


StringStack. Push ("hello");
Cout << stringStack.top () << std::endl;
stringStack.pop ();
stringStack.pop ();
}
Catch (exception const& ex) {
Cerr << "Exception: " << ex. what () <<endl;
Return -1;
}
}

If we compile and run above code, this would produce the following result:

7
Hello
Exception: Stack<>:: pop (): empty stack

7. Write a brief notes on standard template library and standard library container classes.

STANDARD TEMPLATE LIBRARY (STL)


Introduction:
 STL is a collection of generic algorithms and containers that communicate through iterators
 STL is different from normal libraries
 All other libraries defined need entities as classes.
STL COMPONENTS:

19
1. Containers
2. Algorithms
3. Iterators
4. Function Objects
5. Adaptors
6. Allocators
1. Containers
The generic software components used in STL are called containers as they are able to contain objects
within themselves.
Containers are two types:
Sequence containers:
Hold elements in an unordered form as inserted. Some of the sequence containers are
 Vector
 List
 Deque
 Stack
 Queue
Sorted Associative containers:
Hold elements in a sorted form irrespective of insertion and deletion taking place on them.
 Map
 Multimap
 Set
 Multiset
Two types of associative containers are:
Set: This type of containers only store the keys
Map: It stores elements as well as keys
Note: Set and Map accept only one instance of key in the data
Multiset and Multimap store multiple entries of the same key
Header Files of Container Classes:
Header Contents

<vector> An array of T

<list> A doubly linked list of T

20
<deque> A double ended queue of T

<queue> A queue of T

<stack> A stack of T

<map> An associative array of T

<set> A set of T

<bitset> A set of Boolean values

Difference between Sequence container and Sorted associative container:

Sequence container Sorted associative container


Sequence container are able to Sorted associative container are
hold elements in an unordered able to hold elements in an ordered
form as inserted form
Element is accessed by index or Element is accessed by the value of
position of the element key which is a part of the element
Advantages of using containers

 Small in number (few so easy to master)


 Generality
 Efficient, Tested, Debugged and Standardized
 Portable and reusable
Other advantages of using STL containers

 Automatically adjusting growth


 Similar behavior to built in types
 Extensibility
2. Algorithms

STL generic algorithms can be applied to a sequence of elements. They are defined in the following
header file

Header contents

21
<algorithms> A collection of generic algorithms
Advantages of using generic algorithms

 They are Readymade from STL


 They are efficient
 They are standard
 Easy to learn
3. Iterators

Iterators are used like the pointers and can be used to traverse and list out container contents as
below

Header contents
<iterator> Various types of iterators and
iterator support
Two models to manage multiple objects:

Address Mechanism: The pointers to array elements represent a model of address mechanism

Functional Mechanism: The file access using get ( ) and put ( ) use a functional mechanism.

Efficiency of STL iterators depends on two principles:

 Open design having iterators open for programmers to manipulate


 Address manipulation by which the job is possible to be done in minimum steps.

WORKING PRINCIPLE OF STL:

1. CONTAINERS

SEQUENCE CONTAINERS

A sequence container stores the elements in sequence. Some of them are sort, vector, deque, list
etc.

PROGRAM:
1. Vector
2. Generic algorithm: sort( ) with vector
3. List
4. Generic algorithm: find( ) with list
5. Deque

22
6. Stack
7. Queue

1. VECTOR

#include<vector>
#include<string>
#include<iostream>
Using namespace std;
Class Student
{
Int Roll number;
String name;
Public:
Student () {}
Student (int troll number, string tName)
{
Roll number = troll number;
Name = tName;
}
Friend ostream &operator<< (ostream & tempOut, Student student)
{
return tempOut<<tStudent.RollNumber<<”\t”<<tStudent.Name<<endl;
}
};
Void main ()
{
Vector <int> vi;
vi.push_back (11);
vi.push_back (12);
Vector <int>:: iterator intindex;
For (intindex = vi.begin (); intindex<vi.end (); intindex ++)
{
Cout << * intindex << endl;
}
Vector <Student> vs.
Student s1 (1234,”Monit”);
Student s2 (1235,”Rohit”);
vs.push_back (s1);
vs.push_back (s2);
Vector <student>:: iterator student index;
For (student index = vs. begin (); student index<vs.end (); student index ++)
{

23
Cout << * student index << endl;
}
OUTPUT There are two vectors in main ( )
11 vector<int>vi;
12 vector<student>vs.
1234 Monit
1235 Rohit
2. GENERIC ALGORITHM: sort ( ) WITH VECTOR
#include<vector>

#include<algorithm>

#include<iostream>

Using namespace std;

Void main ()

Int number;

Vector<int>vi;

For (int i = 0; i < 10; i++)


{
Cout <<”Enter number [“<< i <<”]”;
Cin >> number;
vi.push _back (number);
}
Vector <int>:: iterator index; //iterator
Cout << “sort in ascending order “<< endl;
Sort (vi .begin (), vi.end ()); //sorting number in ascending
order
For (index = vi.begin (); index<vi.end (); index ++)
{
Cout << * index << “\ t “;
}
Cout << “sort in descending order “<<endl;
Sort (vi.rbegin (), vi.rend ()); //sorting number in descending
order
For (index = vi.begin (); index<vi.end (); index ++)
{
Cout << * index << “\ t “;
}
}

24
OUTPUT
ENTER NUMBER [0] 3
ENTER NUMBER [1] 1
ENTER NUMBER [2] 2
ENTER NUMBER [3] 5
ENTER NUMBER [4] 8

ENTER NUMBER [5] 4

ENTER NUMBER [6] 6

ENTER NUMBER [7] 9

ENTER NUMBER [8] 0

ENTER NUMBER [9] 7

Sort in ascending order

0 1 2 3 4 5 6 7 8 9

9 8765432 10

The statement

Sort (vi.begin (), vi.end ()); in which generic algorithm sort () is called.

3. LIST

List is a container which is similar to a vector.

#include< list>
#include<string>
#include<iostream>
Using namespace std;
Class student
{
Int Roll number;
String name;
Public:
Student () {}
Student (int troll number, string tName)
{
Roll number = troll number;
25
Name = tName;
}
Friend ostream & operator << (ostream & tempout, student tstudent) //essential for print
{
return tempout << tstudent.Rollnumber<<”\t”<< tstudent. Name<<endl;
}
};

Void main ()

List <int> li; //list creation to hold int values

li.push_back (11);

li.push_back (12);

List <int>:: iterator intindex;

For (intindex = li.begin (); intindex! = li.end (); intindex ++)

{
Cout <<*intindex <<endl;
}
List <student>ls; //list creation to hold objects
Student s1 (1234,”Mohit”);
Student s2 (1235,”Rohit”);

Ls. Push _back (s1);


ls. Push _back (s2);
List <student>:: iterator student index // iterator
For (studentindex = ls. Begin (); studentindex! = ls. End (); studentindex ++)
{
Cout <<*studentindex;
}
}
OUTPUT
11

12

1234 Mohit
1235 Rohit

1. GENERIC ALGORITHM: find( ) WITH LIST

#include< list>

26
#include<string>
#include<iostream>
#include<algorithm> //include for find ()
Using namespace std;
Class student
{
Int Roll number;
String name;
Public:
Student () {}
Student (int troll number, string tName)
{

Roll number = troll number;

Name = tName;

Friend ostream & operator << (ostream & tempout, student tstudent) //essential for print
{
Return tempout << tstudent. Roll number <<”\t”<<tstudent. Name <<endl;
}
Bool operator == (student tstudent) //essential for find () to work
{
Return (Name == tstudent. Name);
}
};
Void main ()
{
List <student > ls;
Student s1 (1234, “Mohit”);
Student s2 (1235, “Rohit”);
Student s3 (1236, “Raj”);
Ls .pushback (s1);
Ls .pushback (s2);
Ls .pushback (s3);
List <student >: iterator studentindex;
Student s4 (1237,”Ram”);
studentindex = find (ls . begin (),ls . end(),s2); //finding an object in
list

Ls. Insert (studentindex, s4); //inserting an object

27
For (studentindex = ls. Begin (); studentindex! = ls. End (); studentindex ++)
{
Cout <<*studentindex;

OUTPUT

1234 Mohit

1237 Ram

1235 Rohit

1236 Raj

5. DEQUE

It is a useful container adapted into two other containers namely queue and stack.

#include< deque>
#include<string>
#include<iostream>
Using namespace std;
Class student
{
Int Roll number;
String name;
Public:
Student () {}
Student (int troll number, string tName)
{
Roll number = troll number;
Name = tName;
}
Friend ostream & operator << (ostream & tempout, student tstudent)
{
Return tempout << tstudent. Roll number <<”\t”<<tstudent. Name <<endl;
}
};
Void main ()
{
deque <int>di;
di. Push _front (11);

28
di. Push _front (12);
Deque <int>:: iterator intindex;

For (intindex = di. Begin (); intindex < di.end (); intindex ++)
{
Cout <<*intindex <<endl;
}
deque <student>ds;
Student s1 (1234, “Ram”);
Student s2 (1235,” Ravi”);
Student s3 (1236, “Raja”);
ds.push_front (s1);

ds.push_front (s2);

ds.push_front (s3);

Deque <student >:: iterator studentindex;


For (studentindex = ds. Begin (); studentindex! = ds. End (); studentindex ++)
{
Cout <<*studentindex;
}
}
OUTPUT
12
11
1236 Ravi
1235 Raj
1234 Ram
6. STACK (Adapted Containers)
Stack which follows LIFO (Last in first out) principle. The following program.
#include< stack>
#include<string>
#include<iostream>
Using namespace std;
Class student
{
Public:
Int Roll number;
String name;
Public:

29
Student () {}
Student (int troll number, string tName)
{

Roll number = troll number;

Name = tName;

Friend ostream & operator << (ostream & tempout, student student)

Return (tempout << student. Roll number <<”\t”<<student. Name <<endl;

};

Void main ()

Stack <student>ds;
Student s1 (1234, “Siva”);
Student s2 (1235,” Mani”);
Student s3 (1236, “Ram”);
ds. Push (s1);
ds. Push (s2);
ds. Push (s3);
Student st;
While (! ds. empty ())
{
st = ds. Top ();
Cout <<st. Name <<”\t”<<st. Roll number <<endl;
ds.pop ();
}
}
OUTPUT
Ram 1236

Mani 1235

Siva 1234

7. QUEUE (Adaptive Container)


Queue has the principle of FIFO (First in First out) which is demonstrated in the following program

30
#include< queue>
#include<string>
#include<iostream>
Using namespace std;
Class student
{
Public:
Int Roll number;
String name;
Public:
Student () {}
Student (int troll number, string tName)
{
Roll number = troll number;
Name = tName;
}
Friend ostream & operator << (ostream & tempout, student tstudent)
{
Return tempout << tstudent. Roll number <<”\t”<<tstudent. Name <<endl;
}
};
Void main ()
{
Queue <student>ds;
Student s1 (1234, “Siva”);
Student s2 (1235,” Mani”);
Student s3 (1236, “Ram”);
ds.enqueue (s1);
ds.enqueue (s2);
ds.enqueue (s3);
Student s1;
While (! ds.empty ())
{
st = ds.front ();
Cout << st. Name <<”\t”<<st.Rollnumber <<endl;
ds.dequeue ();
}
}
OUTPUT
Siva 1234

Mani 1235

31
Ram 1236

1.2 SORTED ASSOCIATIVE CONTAINERS:

1. Map
2. Multimap
3. Set
4. Multiset

1. MAP

It is a container which can have two items, a key and a value stored in itself. It is automatically
sorted on the key item at the time of insertion.

#include<map>
#include<string>
#include<iostream>
Using namespace std;
Class student
{
String name;
Public:
Student () {}
Student (string tName)
{
Name = tName;
}
Friend ostream &operator << (ostream & tempout, student tstudent)
{
Return tempout << tstudent. Name;
}
Bool operator < (student tstudent) const
{
Return (Name < tstudent. Name);
}
};
Void main ( )
{
Map<student, int>m1;
Student s1 (“Shabana”);
Student s2 (” Mani”);
Student s3 (“Ilakkiya”);

Student s4 (“Kumar”);

32
m1 [s1] =1;

m1 [s2] =2;

m1 [s3] =3;

m1 [s4] =4;

Map<Student, int>:: iterator Student Index;

For (studentindex = m1.begin (); studentindex! = m1.end (); studentindex ++)

Cout <<studentindex->first<<”/t”;

Cout <<studentindex->second<<endl;

Output:

Kumar 4

Shabana 1

Illakiya 3

Mani 2

2. MULTIMAP
It is a container which can have entry with multiple values for a single key. The function insert (
) is used for inserting an element.
#include<map>
#include<string>
#include<iostream>
Using namespace std;
Class student
{
String name;
Public:
Student () {}
Student (string tName)
{

33
Name = tName;
}
Friend ostream &operator << (ostream & tempout, student tstudent)
{

Return tempout << tstudent. Name;

Bool operator < (student tstudent) const

Return (Name < tstudent. Name);

};

Void main ( )
{
Multimap<student, int>m1;
Student s1 (“IT”);
Student s2 (” CSE”);
Student s3 (“ECE”);
Student s4 (“EEE”);
m1.insert (pair<student, int> (s1, 1));
m1.insert (pair<student, int> (s2, 2));
m1.insert (pair<student, int> (s3, 3));
m1.insert (pair<student, int> (s4, 4));
Multimap<Student, int>::iterator Student Index;
For (studentindex = m1.begin (); studentindex! = m1.end (); studentindex ++)
{
Cout <<studentindex->first<<”/t”;
Cout <<studentindex->second<<endl;
}
}
Output
EEE 4
IT 1
ECE 3
CSE 2
3. SET
The set is a collection of keys in a sorted form. Use include<set> for using sets in a program.

#include<set>

34
#include<vector>

#include<string>

#include<iostream>

Using namespace std;

Class student

Int Roll number;


String name;
Public:
Student () {}
Student (int troll number, string tName)
{
Roll number=troll number;
Name = tName;
}
Friend ostream &operator << (ostream & tempout, student tstudent)
{
Return tempout << tstudent. Roll number<<”\t”<<tstudent. Name<<endl;
}
Bool operator < (student tstudent) const
{
Return (Roll number<tstudent.Rollnumber);
}
};
Void main ( )
{
Set<student>SetStudent;
Student s1 (1234, “IT”);
Student s2 (1235,” CSE”);
Student s3 (1236, “ECE”);
Student s4 ( 1237,”EEE”);

SetStudent.insert (s1);

SetStudent.insert (s2);

SetStudent.insert (s3);

SetStudent.insert (s4);

SetStudent.insert (s1);

35
SetStudent.insert (s2);

SetStudent.insert (s3);

Set<Student>::iterator SetStudentIndex;

For (setstudentindex = setstudent.begin (); setstudentindex! = setstudentindex. End ();

Setstudentindex ++)

Cout <<*setstudentindex;

Output:

1234 IT

1235 CSE

1236 ECE

4. MULTISET

Set can have only a single copy of a key. If more than one copy a key is required, we can use
multiset.
#include<set>
#include<vector>
#include<string>
#include<iostream>

Using namespace std;


Class student
{
Int Roll number;
String name;
Public:
Student () {}
Student (int troll number, string tName)
{
Roll number=troll number;
Name = tName;
36
}

Friend ostream &operator << (ostream & tempout, student tstudent)

Return tempout << tstudent. Roll number<<”\t”<<tstudent. Name<<endl;

}
Bool operator < (student tstudent) const
{
Return (Roll number<tstudent.Rollnumber);
}
};
Void main ( )
{
Multiset<student>multisetStudent;
Student s1 (1234, “IT”);
Student s2 (1235,” CSE”);
Student s3 (1236, “ECE”);
Student s4 ( 1237,”EEE”);
multisetStudent.insert (s1);
multisetStudent.insert (s2);
multisetStudent.insert (s3);
multisetStudent.insert (s1);
multisetStudent.insert (s2);
multisetStudent.insert (s3);
Multiset<Student>::iterator multisetStudentIndex;
For (multisetstudentindex = multisetstudent.begin (); multisetstudentindex! =
multisetstudentindex. End (); multisetstudentindex ++)
{
Cout <<*multisetstudentindex;
}
}
Output:
1234 IT

1234 IT

1235 CSE

1235 CSE

1236 ECE

37
1236 ECE

8. Write a brief notes on standard template library algorithm classes

ALGORITHMS:

STL defines a rich collection of generic algorithms that can be applied to containers and other
sequences.
Programs:
1. Find( ) Algorithm
2. Copy( ) Algorithm
3. Sort( ) Algorithm

1. Find ( ) Algorithm
The generic algorithm find ( ) locates an element within a sequence.
#include<deque>
#include<string>
#include<iostream>
#include<algorithm> //include for find ()
Using namespace std;
Class student
{
Int Roll number;
String name;
Public:
Student () {}
Student (int troll number, string tName)
{
Roll number = troll number;
Name = tName;
}
Friend ostream & operator << (ostream & tempout, student tstudent)
{
Return tempout << tstudent. Rollnumber <<”\t”<<tstudent. Name <<endl;
}
Bool operator = = (student tstudent) const //it is must for find ()
{

38
Return (Roll Number = = tstudent .RollNumbe);
}
};

Void main ()

Vector <student>vs.; //vector creation


Student s1 (1234,”IT”);
Student s2 (1235,”CSE”);
Student s3 (1236,”ECE”);
vs.push_back (s1); \\inserting element in to the vector
vs.push_back (s2);
vs.push_back (s3);
Cout <<”finding the object s2 in the vector “<<endl;
Vector<student>::iterator vector index;
Vector index = find (vs. begin (), vs.end (), s2);
Cout <<*vector index;
List<student>ls (vs. begin (), vs . . . end ()); //list creation from the vector data
Cout <<”finding the object s2 in the vector “<<endl;
List <student>::iterator list index;
List index = find (ls. Begin (), ls. End (), s2);
Cout <<*list index;
Deque <student>ds (vs. begin (), vs.end ()); //deque creation from the vector data
Cout <<”finding the object s2 in the deque “<<endl;
Deque <student >:: iterator dequeindex;
Dequeindex = find (ds. Begin (), ds. End (), s2);
Cout <<*dequeindex;
}
OUTPUT

Finding the object s2 in the vector

1235 CSE

Finding the object s2 in the list

1235 CSE

Finding the object s2 in the deque

1235 CSE

2. Copy ( ) Algorithm

39
The generic algorithm copy ( ) is used to copy a sequence of objects to a specified target.

#include<vector>
#include< list>
#include<deque>
#include<string>
#include<iostream>
#include<algorithm>
Using namespace std;
Class student
{
Int Rollnumber;
String name;
Public:
Student () {}
Student (int troll number, string tName)
{
Rollnumber = troll number;
Name = tName;
}
Friend ostream & operator << (ostream & tempout, student student)
{
Return (tempout << student. Rollnumber <<”\t”<<student. name <<endl;
}
};
Void main ()
{
Vector <student>v1; //vector v1 creation
Student s1 (1234,”IT”);
Student s2 (1235,”CSE”);
Student s3 (1236,”ECE”);
v1.push_back (s1); //inserting element in to the vector
v1.push_back (s2);
v1.push_back (s3);
Vector <student> v2 (v1.size ()); //vector v2 creation
Copy (v1.begin (), v1.end (), v2. begin ()); //copy v1 to v2

Cout<<”The content of the vector v2”<<endl;

Vector <student>::iterator vectorindex;

For (vectorindex = v2.begin (); vectorindex! =v2.end (); vectorindex++)

40
Cout <<”vectorindex; //print content of v2

list <student>l1(v1.size());
Copy (v1.begin (), v1.end (), l1.begin ());
List<student>:: iterator listindex;
Cout <<”The content of list l1”<<endl;
For (listindex = l1.begin (); Listindex! =l1.end (); Listindex++)
{
Cout <<”listindex; //print content of 11
}
Deque <student>d1 (v1.size ());
Copy (v1.begin (), v1.end (), d1.begin ());
Deque<student>::iterator dequeindex;
Cout <<”The content of deque d1”<<endl;
For (dequeindex = d1.begin (); dequeindex! =d1.end (); dequeindex++)
{
Cout <<*dequeindex; //print the content of d1
}
}
OUTPUT

The content of vector v2


1234 IT

1235 CSE

1236 ECE

The content of the list l1

1234 IT

1235 CSE

1236 ECE

The content of the deque d1

1234 IT

1235 CSE

1236 ECE

3. Sort ( ) Algorithm

41
Sort ( ) takes two argument of type const iterator that point with the beginning and end of the
sequence. When sort ( ) operates on a container, it uses the relational operators = = and < of the
containers element.
#include<vector>
#include< list>
#include<deque>
#include<string>
#include<iostream>
#include<algorithm>
Using namespace std;
Void main ( )
{
int number;
Vector<int>vi;
For (int i=0; i<4; i++)
{
Cout<<”Enter number [“<<i<<”]”;
Cin>>number;
vi.push_back (number);
}
Vector<int>::iterator index1;
Cout<<”\n Sorting the vector in ascending order”<<endl;
Sort (vi.begin ( ), vi.end ( ));
For (index1=vi.begin ( ); index1<vi.end ( ); index1++)
{
Cout<<*index1<<”\t”;
}
Cout<<”\n Sorting the deque in ascending order”<<endl;
Deque<int>de (vi.begin ( ), vi.end ( ));
Sort (de.begin ( ), de.end ( ));
Deque<int>::iterator index2;
For (index2=de.begin ( ); index2<de.end ( ); index2++)
{
Cout<<*index2<<”\t”;

OUTPUT:
Enter number [0] 12

42
Enter number [1] 4
Enter number [2] 34
Enter number [3] 76
Sorting the vector in ascending order
4 12 34 76

Sorting the deque in ascending order


4 12 34 76
9. What is a generic function? [aug 2011]
Generic is a form of abstraction in developing code. Instead of writing a function or a class for a
particular type, it can be written generally to use any type. When an instance of the generic class is
instantiated, the type is specified.

Eg. You might create a generic sorting class and when you create an instance of this, the type of
entity it sorts is specified. One instance might sort ints, another doubles, and another payroll records.

ConceptC++ boasts many features that directly support Generic Programming. The major features
are:

 Concepts: Concepts are sets of requirements bundled together under a single name. There
are several types of requirements, but the most common kinds are (1) functions, constructors,
and operators that the data types must have and (2) associated types that are typically used
to express those functions, constructors, and operators. ConceptC++ concepts can directly
express refinement relationships, nested requirements, etc., so that all important syntactic
features of concepts can be encoded directly in ConceptC++.
 Concept maps: Concept maps state how a set of types meets the requirements of a concept,
and are ConceptC++'s implementation of models. They are the "glue" that makes it possible to
map from whatever syntax the user types use to the syntax required by the algorithms that
use those concepts, giving ConceptC++ complete support for retroactive modeling. This glue
makes templates more reusable, because you don't have to change your types to use them
with a generic algorithm, even if the algorithm uses a completely different syntax!
 Requirements clauses: Requirements clauses state the requirements that are placed on a
template. The user must be sure to meet all of those requirements are met when using the
template, but also the author of the template may only use what has been required: thus,
ConceptC++ gives complete type-checking of templates at definition time. This means that
errors in the definition of templates will be caught at definition time, so they won't slip through
to users of a library. It also means that when a template is misused (i.e., the requirements of
the template, as expressed in the requirements clause, are not met), a ConceptC++ compiler
can produce clean, concise error messages describing the problem.
 Concept-based overloading: Crucial for performance, ConceptC++ fully supports both
specialization based on concepts and concept-based overloading, by extending C++'s rules for
specialization and partial ordering of function templates.
 A concept-enabled Standard Library: Many of the algorithms in the ConceptC++ Standard
Library use concepts in their descriptions. Although this change is mainly transparent to users--
almost all code still works as it did before--mistakes that used to generate horribly long error

43
messages now produce short, meaningful error messages. Moreover, users can enjoy the
benefits of retroactive modeling with Standard Library algorithms.

10. Write a c++ program for generic bubble sort? [aug 2011]

#include <iostream.h>
using namespace std;

template <class X> void bubble(X *items,int count)


{
X t;

for(int a=1; a<count; a++)


for(int b=count-1; b>=a; b--)
if(items[b-1] > items[b]) {
t = items[b-1];
items[b-1] = items[b];
items[b] = t;
}
}

int main()
{
int iarray[7] = {7, 5, 4, 3, 9, 8, 6};
double darray[5] = {4.3, 2.5, -0.9, 10.2, 3.0};

Cout << "Here is unsorted integer array: ";


for(int i=0; i<7; i++)
Cout << iarray[i] << ' ';
Cout << endl;

bubble(iarray, 7);
Cout << "Here is sorted integer array: ";
for(int i=0; i<7; i++)
Cout << iarray[i] << ' ';
Cout << endl;
Cout << "Here is unsorted double array: ";
for(int i=0; i<5; i++)
Cout << darray[i] << ' ';
Cout << endl;
bubble(darray, 5);

Cout << "Here is sorted double array: ";


for(int i=0; i<5; i++)
Cout << darray[i] << ' ';
Cout << endl;
return 0;
}

44
Here is unsorted integer array: 7 5 4 3 9 8 6
Here is sorted integer array: 3 4 5 6 7 8 9
Here is unsorted double array: 4.3 2.5 -0.9 10.2 3
Here is sorted double array: -0.9 2.5 3 4.3 10.2

11. write a c++ program using lists form stl to input 10 numbers and store them in a list.
from the list create two more lists; one containing the even numbers and other contain
the odd numbers. output all the three lists.
Program:
# include<iostream>
# include<list>
Using namespace std;
int main( )
{
list<int>lst;
list<int>odd;
list<int>even;
int i;
For (i=0; i<10; i++)
lst.push_back (rand ( ));
Cout<<”Original list :”<< endl;

p=lst.begin ( );

While (p! =lst.end ( ))


{
If (*p/2= =0) then
even.push_back (*p);
else
odd.push_back(*p);
p++;
}
List<int>:: iterator p=even.begin ( );

45
While (p! =even.end ( ))
{
Cout<<*p<<” “;
p++;
List<int>:: iterator p=odd.begin ( );
While (p! =odd.end ( ))
{
Cout<<*p<<” “;
p++;
Return 0;
}

46

You might also like