gpt4 book ai didi

c++ - 如何在运行时在 C++ 中创建和增加数组的大小

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:44 27 4
gpt4 key购买 nike

我想创建一个数组,其大小我只在运行时知道,然后在程序执行期间进一步增加该大小。
这是来自/r/dailyprogrammer 的挑战,可以在这里找到 https://www.reddit.com/r/dailyprogrammer/comments/3twuwf/20151123_challenge_242_easy_funny_plant/
MSVisual 给我错误 std::badd_array_new_length 这意味着它在实例化数组时遇到问题?
我厌倦了经常从它工作的网站上逐个复制代码字母,而且我经常出错。 Visual 是学习 C++ 的糟糕平台吗?我应该试试 QT 吗?

#include <iostream>
#include <string>
void main(int argc, char* argv[]) {

int currentPlants = std::stoi(argv[2]), targetPeople = std::stoi(argv[1]), currentProduce = 0, week = 0;
int * plants;
plants = new int[currentPlants];
for (int i = 0; i < currentPlants; i++) {
plants[i] = 0;
}

if (plants == nullptr) EXIT_FAILURE;

while (currentProduce < targetPeople) {
currentProduce = 0;
for (int i = 0; i < currentPlants; i++) {
currentProduce += plants[i];
plants[i]++;
}
if (currentProduce >= targetPeople) break;
else {
plants = new int[currentProduce];
for (; currentPlants < currentProduce; currentPlants++) {
plants[currentPlants] = 0;
}
}

week++;
}
std::cout << week;
}

最佳答案

您应该使用 std::vector

总结:

// Create an array of size 10    
std::vector<int> my_vector(10);

// Add '3' to my_vector
my_vector.push_back(3);

// Remove the last element
my_vector.pop_back();

此处的解释和示例:www.cplusplus.com/reference/vector/vector/

编辑:构造对象时不需要指定数组大小。

// Create an array    
std::vector<int> my_vector;

关于c++ - 如何在运行时在 C++ 中创建和增加数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325872/

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