c++ pta模板题 vector

c++ pta模板题 vector

本题要求实现一个Vector类模板,能实现数据的存储和访问。通过[]运算符访问时只能访问已经存在的元素,而通过add()方法访问时可以自动扩展内部存储空间。

注意,这个Vector的行为和std::vector是不同的

函数接口定义:

 template <class T>
class Vector {
...

裁判测试程序样例:

#include <iostream>
using namespace std;

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

int main()
{
    Vector<int> vint;
    int n,m;
    cin >> n >> m;
    for ( int i=0; i<n; i++ ) {
        //    add() can inflate the vector automatically
        vint.add(i);    
    }
    //    get_size() returns the number of elements stored in the vector
    cout << vint.get_size() << endl;
    cout << vint[m] << endl;
    //    remove() removes the element at the index which begins from zero
    vint.remove(m);
    cout << vint.add(-1) << endl;
    cout << vint[m] << endl;
    Vector<int> vv = vint;
    cout << vv[vv.get_size()-1] << endl;
    vv.add(m);
    cout << vint.get_size() << endl;
}

输入样例:

100 50

输出样例:

100
50
99
51
-1
100

代码:

template <class T>
class Vector
{
private:
    int pos;
    int size = 100;
    T* data;
public:
    Vector() {
        pos = 0;
        data = new T[size];
    }
    int add(T m) {
        data[pos]=m;
        pos++;
        return pos-1;
    }
    int get_size() { return pos; }
    void remove(int m) {
        for (int i = m; i < pos-1; i++) {
            data[i] = data[i + 1];
        }
        pos--;
    }
    const T& operator[](int index)const
    {
        return data[index];
    }
};
  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值