Question

I've got this small piece of code

int row[7];
bool equals = false;

std::vector<int>range;

for(int i = 1; i <= 35; ++i)
{
    range.push_back(i);
}

for(int i = 0; i < 7; i++){
    int number = range[rand() % range.size() + 1];
    std::vector<int>::iterator pos = find(range.begin(), range.end(), number);
    row[i] = number;

    range.erase(range.begin() + (*pos - 1));
    std::cout << row[i] << endl;
}
return 0;

It takes away random elements from the vector, the problem I've got is that every time I remove a object from the vector the size updates but the positions doesn't seem to change on the individual numbers in the vector, making the program crash since I sometimes travel outside the bounds of the vector.

I've tried with vector::shrink_to_fit but it didn't seem to re-evaluate the vectors item positions.

What am I missing? It seems like such a simple thing to do but I just can't wrap my head around it.

P.S I'm a c++ scrub so if you have any input on the code being bad/unsafe I'm open for suggestions/constructive criticism.

Was it helpful?

Solution

rand() % range.size() + 1

can go outside the bounds of the vector use

rand() % range.size()

use this piece of code instead :

std::vector<int>range;

for(int i = 1; i <= 35; ++i)
{
    range.push_back(i);
}
srand(time(0)) ;
for(int i = 0; i < 7; i++){
    int index = rand() % range.size() ;
    int number = range[index];
    row[i] = number;
    range.erase(range.begin() + index);
    std::cout << row[i] << endl;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top