c++ garbage values in vector of pointer

前端 未结 6 1963
青春惊慌失措
青春惊慌失措 2020-12-22 00:12

When I do:

for(i=0; i

s

6条回答
  •  抹茶落季
    2020-12-22 00:31

    This is because the vector reallocated its internal storage when it grows beyond its current capacity; after the reallocation, the address of elements may have changed.

    You can avoid reallocation by reserving a big enough storage beforehand:

    vectorA.reserve(size);
    //vectorB.reserve(size); // this would not hurt either
    for(i=0; i

    One final note: if you can use C++11, emplace_back constructs your object in place, hence, without copying.

提交回复
热议问题