I have this code, and I've generated an array of random number twice... Now, I just want to insert these numbers in to the vector upon execution.
I am using Microsoft Visual Studio.
This is my code:
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++)?
You cannot add elements to an array. An array never has more nor less elements than it had when it was first created.
You can add elements to a vector "upon compilation" by using a constructor. Techically the elements are still added at runtime, unless the compiler does some optimization.
During execution, you can use std::vector::push_back
or one of the other member functions that std::vector
has.
As a sidenote: Calling srand
before every other call to rand
is a great way to make sure that the numbers returned by rand
are not at all random. Secondly rand() % 20 + 1
is not "between 1 and 100" as the comment suggests. Thirdly, you pointlessly overwrite elements in the loop. Fourthly, you didn't initialize all of the elements in the array pointed by randNum
before using them.