Allocation vector of vector

0

I have a vector of vector built in the following way:

std::vector<std::vector<int>> symbols;

I want to insert some int in the structure. To do this, I want to check that the position in which the int will be inserted is legal. I'm trying to make the vector growing up in a dynamic way. For this reason, I wrote the following code:

void checkIndex(unsigned int i0, unsigned int i1) {
int mult_fac=2;
if(i0>=symbols.capacity()-1){
    symbols.reserve((i0+1)*mult_fac);

}
if(i1>=symbols[i0].capacity()-1){
    symbols[i0].reserve((i1 + 1)*mult_fac);
}

}

To verify that all of this works, I wrote a main:

int main() {

for(;;){
    int i=rand()%1000;
    int j=rand()%1000;
    checkIndex(i,j);
}
return 0;}

But, the output shows a bad memory access:

"Process finished with exit code -1073741819 (0xC0000005)"

I'm using Windows 10. I can't understand how to fix it! Thanks for helping me.

c++
vector
stdvector
asked on Stack Overflow Apr 16, 2020 by Martina_bxxu

1 Answer

0

The obvious problems are that capacity() doesn't tell you the size of the vector, you need size() instead and that reserve() doesn't change the size of the vector, you need resize() instead.

Finally your tests are too pessimistic, after changing caapcity for size you could just have

if (i0 >= symbols.size()) {

and

if (i1 >= symbols[i0].size()) {

You don't need the -1 in there, an index is invalid if it is >= to the size.

answered on Stack Overflow Apr 16, 2020 by john • edited Apr 16, 2020 by john

User contributions licensed under CC BY-SA 3.0