C++ - Unit V
C++ - Unit V
PART A:
1. What is a 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
Class classname
T1 data1;
….
1
};
template<class T…>
…..
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?
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
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.
2
a) Base Type
b) Compound Type
c) Container Type
3) Property iterators.
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
Real times Information is a mechanism by which we can find the type of an object are run
time.
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.
Reinterpret cast
Dynamic cast
Static cast
Const_cast
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:
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.
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
The collection of these generic classes and functions is called the Standard Template Library
1) Container
2) Algorithm
3) Iterators.
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
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
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:
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:
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 >.
Int main ()
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:
Public:
T kind [16];
T* drive ();
// ...
};
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;
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};
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:
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
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
#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->Show ( );
PtrOne->Show ( );
Sample Output
12 20 10
Just as we can define function templates, we can also define class templates. The general form
of a generic class declaration is shown here:
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>
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 ();
}
};
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
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.
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
20
<deque> A double ended queue of T
<queue> A queue of T
<stack> A stack of T
<set> A set of T
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
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.
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>
Void main ()
Int number;
Vector<int>vi;
24
OUTPUT
ENTER NUMBER [0] 3
ENTER NUMBER [1] 1
ENTER NUMBER [2] 2
ENTER NUMBER [3] 5
ENTER NUMBER [4] 8
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
#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 ()
li.push_back (11);
li.push_back (12);
{
Cout <<*intindex <<endl;
}
List <student>ls; //list creation to hold objects
Student s1 (1234,”Mohit”);
Student s2 (1235,”Rohit”);
12
1234 Mohit
1235 Rohit
#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)
{
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
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);
29
Student () {}
Student (int troll number, string tName)
{
Name = tName;
Friend ostream & operator << (ostream & tempout, student student)
};
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
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. 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;
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)
{
};
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>
Class student
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;
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>
}
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
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 ()
1235 CSE
1235 CSE
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
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
1235 CSE
1236 ECE
1234 IT
1235 CSE
1236 ECE
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
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;
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};
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);
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 ( );
45
While (p! =even.end ( ))
{
Cout<<*p<<” “;
p++;
List<int>:: iterator p=odd.begin ( );
While (p! =odd.end ( ))
{
Cout<<*p<<” “;
p++;
Return 0;
}
46