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

Scy*_*Scy 0 c++ arrays

我想创建一个数组,其大小我只会在运行时知道,然后在执行程序时进一步增加该大小.
这是来自/ 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;    
}
Run Code Online (Sandbox Code Playgroud)

Pie*_*rre 5

你应该使用一个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();
Run Code Online (Sandbox Code Playgroud)

这里的解释和示例:www.cplusplus.com/reference/vector/vector/

编辑:构造对象时无需指定数组大小.

// Create an array    
std::vector<int> my_vector;
Run Code Online (Sandbox Code Playgroud)

  • 作为评论很好,但显然不是真正的答案。(不过,这不是我的反对票。) (2认同)