如何在 execution/compilation (c++) 上向 array/vector 添加元素?

How do you add element to array/vector upon execution/compilation (c++)?

我有这段代码,我生成了一个随机数数组两次... 现在,我只想在执行时将这些数字插入向量中。

我正在使用微软 Visual Studio。

这是我的代码:

using namespace std;

int main() {

int gRows, gCols;

std::cout << "Enter Rows: " << std::endl;
std::cin >> gRows;
std::cout << "Enter Cols: " << std::endl;
std::cin >> gCols;

std::vector<std::vector<int>> cGrid;

int numOfElem = gRows*gCols;
int* randNum = new int[numOfElem];

for (int x = 0; x < (numOfElem / 2); x++) {
    srand((unsigned int)time(0));
    const int fNum = rand() % 20 + 1; //generate num between 1 and 100
    const int sNum = rand() % 20 + 1;
    randNum[x] = fNum;
    randNum[x + 2] = sNum;
}

for (int y = 0; y < numOfElem; y++) {
    std::cout << randNum[y] <<std::endl;
}

//int i = 0;

for (int nRows = 0; nRows < gRows; nRows++) {// for every row and column
    for (int nCols = 0; nCols < gCols; nCols++) {
        cGrid[gRows][gCols] = 0;//card at that coordinate will be equal to
        std::cout << cGrid[gRows][gCols];
        //i = i + 1;
    }
    std::cout << std::endl;
}}

How do you add element to array/vector upon execution/compilation (c++)?

您不能向数组中添加元素。数组的元素永远不会比它最初创建时多或少。

您可以使用构造函数将元素添加到向量 "upon compilation"。从技术上讲,元素仍然在运行时添加,除非编译器进行一些优化。

在执行期间,您可以使用 std::vector::push_backstd::vector 具有的其他成员函数之一。

旁注:在每次调用 rand 之前调用 srand 是确保 rand 返回的数字完全不是随机的好方法。其次 rand() % 20 + 1 不是评论所暗示的 "between 1 and 100" 。第三,您毫无意义地覆盖了循环中的元素。第四,在使用 randNum 指向的数组中的所有元素之前,您没有初始化它们。