gpt4 book ai didi

c++ - 尝试动态增加数组大小

转载 作者:行者123 更新时间:2023-11-28 05:26:15 26 4
gpt4 key购买 nike

我正在开发一个程序,用户不断输入数字,这些数字被保存到一个数组中,当数组已满时,我试图将原始数组复制到一个新数组中并继续填充该数组,但是我不能让它工作。到目前为止,这是我的代码

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

int main()
{
int size;
cout << "Please enter how many numbers you want to enter: ";
cin >> size;
double *array = new double*[size];
cout << "Please enter your numbers: ";
for(int i = 0; i < size; i++) {
cin >> array[i];
if(i == size-1) {
int newSize = 2*size;
double *arrayb = new double*[newSize];
for(int i = 0;i<size;i++) {
arrayb[i] = array[i];
}
delete [] array;
array = arrayb;
size = newSize;
}
}
}

最佳答案

如果在执行前不知道集合的最大大小,则需要避免使用数组。正如 TartanLlama 所说,您可以使用 std::vector。 Vector 允许您根据需要添加项目。但是有很多容器具有不同的访问方法。请参阅此链接以初步了解如何选择您的容器: In which scenario do I use a particular STL container?

关于c++ - 尝试动态增加数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40485030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com