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

vector类的实现,动态内存越界问题

vector类的实现,动态内存越界问题
这是另一个博主的问题,我的疑惑是,如果输入的n>一开始设置的size=100,那么在add函数中不会出现越界吗?

#include 
using namespace std;
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];
    }
};
int main()
{
    Vector<int> vint;
    int n,m;
    cin >> n >> m;
    for ( int i=0; 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;
}

  • 写回答

4条回答 默认 最新

  • CSDN专家-link 2022-11-16 12:38
    关注

    肯定越界啊,这代码并没有考虑这种情况

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

报告相同问题?

问题事件

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

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上