6-62.简易的动态数组类模板

本题要求实现一个简易的MyVector模板类,具有构造函数、析构函数、拷贝构造函数、输出函数display,读入赋值函数set。能实现各种类型简易的动态数组类模板。Point类与主函数已写好,你只要将MyVector模板类进行定义并实现其成员函数。
已有的Point类型定义如下:

输入格式分三行输入

第一行:输入一个整数,代表要创建的数组类型(1-Int,2-float,3-Point,其它代表出错)

第二行:输入一个整数n,要创建的数组的元素个数

第三行:输入n个对应的数组元素(n个整数,n个实型数据,n组坐标(x,y值空格隔开。

### 输入样例:

在这里给出一组输入。例如:

3

4

1 1 2 5 3 6 -1 -2

输出样例:

程序运行的时候先是在屏幕上显示:
1: ArrayInt
2: ArrayFloat
3: ArrayPoint
What are you create ?: //等待输入你的选择1,-3,例如按3,将建立以点对象数组。则输出点坐标

1: ArrayInt

2: ArrayFloat

3: ArrayPoint

What are you create ?: 

 (1,1) (2,5) (3,6) (-1,-2)

代码实现:

#include  <iostream>
using  namespace  std;
class  Point
{    
public:
        Point(int  x=0,int  y=0):x(x),y(y){}
        void  set(int  x=0,int  y=0)
        {this->x=x;this->y=y;}
        friend  ostream&  operator<<(ostream  &out,Point  &p)
        {    out<<'('<<p.x<<','<<p.y<<')';
              return  out;
        }
        friend  istream&  operator>>(istream  &in,Point  &p)
        {      in>>p.x>>p.y;
                return  in;
        }
private:
        int  x,y;
};

/*你的代码将嵌到这里*/
template<typename T>
class MyVector{
	private:
		T *vec;
		int size;
	public:
		MyVector(int n){
			vec = new T[n];
			size = n;
		}
		void set(){
			for(int i=0;i<size;i++){
				cin>>vec[i];
			}
		}
		void display(){
			for(int i=0;i<size;i++){
				cout<<vec[i]<<" ";
			}
		}
};

void  menu()
{  
    cout<<"1:  ArrayInt\n2:  ArrayFloat\n3:  ArrayPoint\n";
    cout<<"What  are  you  create  ?:\n";
}

void  CreateArrayInt()
{
    int  n;  cin>>n;
    MyVector<int>  A(n);
    A.set();
    A.display();
}

void  CreateArrayFloat()
{
    int  n;  cin>>n;
    MyVector<float>  A(n);
    A.set();
    A.display();
}

void  CreateArrayPoint()
{
    int  n;  cin>>n;
    MyVector<Point>  A(n);
    A.set();
    A.display();
}

int  main()
{  int  choice;
    menu();
    cin>>choice;
    switch(choice)
    {  case  1:  CreateArrayInt();  break;
        case  2:  CreateArrayFloat();  break;
        case  3:  CreateArrayPoint();  break;
        default:  cout<<"ERROR";break;
    }
return  0;
};

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值