Week 23 solutions
23a) Write a C++ program to write a function template
for finding the minimum value contained in any array.
Program:
#include<iostream>
#include<vector>
using namespace std;
template<class T>
T min(T a[],T n)
{
T temp=a[0];
for (int i = 0; i <n; ++i)
{
if(temp>=a[i])
temp=a[i];
}
return temp;
}
int main()
{
int a[20];
int n=0,res;
cout<<"Enter the elements of array\n";
while(cin>>a[n])
{
n++;
}
res=min(a,n);
cout<<"Minimum of all elements is :"<<res<<endl;
}
Output:
Enter the elements of array
25
7
9
36
55
77
8
2
*
Minimum of all elements is :2
23b) Write a template function that takes a vector<T> vt and a vector<U> vu
as arguments and returns the sum of all vt[i]*vt[i]s.
program:
#include<iostream>
#include<vector>
using namespace std;
vector<double>vt,vu;
template<class T>
T value(vector<T>a,vector<T>b)
{
T sum=0;
for(int i=0;i<a.size();i++)
{
cout<<a[i]<<"\t"<<b[i]<<"\t"<<a[i]*b[i]<<endl;
sum+=a[i]*b[i];
}
return sum;
}
int main()
{
double p,w;
double val;
cout<<"Enter the elements of two vectors sinultaneously (enter character to quit)\n";
cout<<"\n----------Reading values-------- \n";
while(cin>>p&&cin>>w)
{
vt.push_back(p);
vu.push_back(w);
}
val=value(vt,vu);
cout<<"\nSum of products is : ="<<val<<endl;
}
output:
Enter the elements of two vectors sinultaneously (enter character to quit)
----------Reading values--------
1 2
2 3
3 4
4 5
6 10
*
1 2 2
2 3 6
3 4 12
4 5 20
6 10 60
Sum of products is : =100
23c) Define a class Int having a single member of class int. Define
constructors, assignment,and operators +,-,*,/ for it.
program:
#include <iostream>
using namespace std;
class Int
{
public:
int a;
};
int main()
{
Int x;
int b;
cout<<"Enter an integer :\n";
cin>>b;
x.a=b;
cout<<"\nvalue of a is:"<<x.a;
x.a+=10;
cout<<"\nAfter adding 10 value of a is:"<<x.a;
}
output:
Enter an integer :
22
value of a is:22
After adding 10 value of a is:32
23d) Implement vector::operator=() using an allocator for memory management
program:
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector<int> foo (3,0);
vectorlt;int> bar (5,0);
bar = foo;
foo = vector<int>();
cout << "Size of foo: " << int(foo.size()) << '\n';
cout << "Size of bar: " << int(bar.size()) << '\n';
return 0;
}
output:
Size of foo: 0
Size of bar: 3
No comments:
Post a Comment