-2

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;
}}
DVilela
  • 3
  • 1
  • [x] and [x+2] and x++ look funny. – Bathsheba Apr 13 '16 at 15:34
  • 3
    Calling `srand()` in every iteration is a bad idea. See [c - srand() — why call it only once?](http://stackoverflow.com/questions/7343833/srand-why-call-it-only-once). – MikeCAT Apr 13 '16 at 15:36
  • I don't think the first loop is doing what you think. It's only filling in `randNum` up to `numOfElem/2 + 2`, but then you print all the elements of `randNum`. – Barmar Apr 13 '16 at 15:42
  • And `rand() % 20 + 1` generates a number between 1 and 20, not between 1 and 100. – Barmar Apr 13 '16 at 15:42
  • @MikeCAT that's true, I thought the was the way of generate the same numbers twice but it seems to only for for the size of 4, know any ways of generating the same number twice? – DVilela Apr 14 '16 at 07:54
  • @DVilela Why not store generated numbers and use them for "the second time"? – MikeCAT Apr 14 '16 at 08:24

1 Answers1

0

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326