z__y 2022-11-16 10:48 采纳率: 88.9%
浏览 12
已结题

Vector类实现,动态内存下标越界

Vector类实现,动态内存下标越界
这是另一个博主的代码,我的疑惑是,如果输入的n超过初始设置的100,add()函数里不会造成下标越界吗

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];
    }
};
————————————————
版权声明:本文为CSDN博主「我不想起名字呀」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_47867028/article/details/117336559

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 size:" << vint.get_size() << endl;
    cout << "vv size:" << vv.get_size() << endl;
    cout << vint.get_size() << endl;
}

  • 写回答

3条回答 默认 最新

  • 关注

    size在构造函数里初始化
    size=10放在构造函数里。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 11月28日
  • 已采纳回答 11月20日
  • 创建了问题 11月16日

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?