利用函数模板解决双倍功能 利用类模板解决绝对值功能 vector应用测试

发布时间 2023-05-26 18:20:49作者: 不如喝点

请使用模板参数设计实现双倍功能函数,函数功能要求实现返回值为输入参数的两倍,函数参数应能适应整型、浮点型、双精度型等各种类型,返回值类型与参数一样。

裁判测试程序样例:

 
#include <iostream>
using namespace std;

/*请在这里填写答案*/

int main(void){
    char c='\0';
    int i=0;
    long l=0;
    scanf("%c%d%ld",&c,&i,&l);
    cout<<Double(c)<<endl;
    cout<<Double(i)<<endl;
    cout<<Double(l)<<endl;
    float f=1.1;
    double d=2.2;
    scanf("%f%lf",&f,&d);
    cout<<Double(f)<<endl;
    cout<<Double(d)<<endl;
    return 0;
}
 

输入样例:

0
1
200000
3.45
6.789
 

输出样例:

`
2
400000
6.9
13.578




template<class T>
T Double(T x)
{
return 2*x;
}

 

 

 

 

 

请使用模板参数设计实现绝对值模板类Absolute,Absolute类功能要求成员函数getValue(void)const计算类数据的绝对值,类数据类型应能适应整型、浮点型、双精度型等各种类型,绝对值类型与类数据一样。

裁判测试程序样例:

 
#include <iostream>
using namespace std;

/*请在这里填写答案*/

int main(void){
    char c='\0';
    int i=0;
    long l=0;
    scanf("%c%d%ld",&c,&i,&l);
    float f=1.1;
    double d=2.2;
    scanf("%f%lf",&f,&d);
    Absolute<char> dc(c);
    cout<<dc.getValue()<<endl;
    Absolute<int> di(i);
    cout<<di.getValue()<<endl;
    Absolute<long> dl(l);
    cout<<dl.getValue()<<endl;
    Absolute<float> df(f);
    cout<<df.getValue()<<endl;
    Absolute<double> dd(d);
    cout<<dd.getValue()<<endl;
    return 0;
}
 

输入样例:

a
-2
300000
-4.56
7.89
 

输出样例:

a
2
300000
4.56
7.89






template<class T>
class Absolute
{
public:
T x;
Absolute(T y)
{
x=y;
}
T getValue(void)const
{
if(x<0)
return 0-x;
else
return x;
}
};

 

 

 

 

 

 

 

 

 

 

应用STL中的vector完成功能测试。

设计要求:

 
定义一个空的vector,将用户输入的数组a[10]的10个数插入到vector中,在vector头部插入数b,用迭代器遍历vector并输出其中的元素值。然后将vector从小到大排序,删除vector尾部的元素,用迭代器遍历vector并输出其中的元素值。最后将vector清空。
 

裁判测试程序样例:

 
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(void)
{
    int i,a[10],b;
    for(i=0; i<10; i++){
        scanf("%d",&a[i]);
    }
    scanf("%d",&b);//插入的数
    {

/*请在这里填写答案*/

    }
    return 0;
}
 

输入样例:

9 8 7 6 5 4 3 2 1 10
0
 

输出样例:

[0][9][8][7][6][5][4][3][2][1][10]
[0][1][2][3][4][5][6][7][8][9]




vector<int> v;
for(i=0;i<10;i++)
{
v.push_back(a[i]);
}
v.insert(v.begin(),b);
vector<int>::iterator it;
for(it=v.begin();it!=v.end();it++)
{
cout<<"["<<*it<<"]";
}
cout<<endl;
sort(v.begin(),v.end());
v.pop_back();
for(it=v.begin();it!=v.end();it++)
{
cout<<"["<<*it<<"]";
}
v.clear();