Pergunta

Please look at the small test code + output provided below. It seems that when using push_back() on an std::vector within a loop, C++ allocates the memory at 'random' addresses, and then re-copies the data into consecutive memory addresses after the loop is finished.

Is this to do with the fact that the size of the vector is not known before the loop?

What is the correct way of doing what I do in the test code? Do I have to assign the pointers in another loop after the first one exits? Note that I cannot define the size of the vector before the first loop, because in reality it is actually a vector of class objects that require initialization.

Thank you for your help.

std::vector<int> MyVec;
std::vector<int *> MyVecPtr;

for (int i = 0; i < 10; i++)
{
    MyVec.push_back(i);

    MyVecPtr.push_back(&MyVec.back());

    std::cout << MyVec.back() << " " 
              << &MyVec.back() << " "
              << MyVecPtr.back() << " "
              << *MyVecPtr.back() << std::endl;
}

std::cout << std::endl;

for (int i = 0; i < MyVec.size(); i++)
{
    std::cout << MyVec[i] << " " 
              << &MyVec[i] << " "
              << MyVecPtr[i] << " "
              << *MyVecPtr[i] << std::endl;
}

0 0x180d010 0x180d010 0
1 0x180d054 0x180d054 1
2 0x180d038 0x180d038 2
3 0x180d03c 0x180d03c 3
4 0x180d0b0 0x180d0b0 4
5 0x180d0b4 0x180d0b4 5
6 0x180d0b8 0x180d0b8 6
7 0x180d0bc 0x180d0bc 7
8 0x180d140 0x180d140 8
9 0x180d144 0x180d144 9

0 0x180d120 0x180d010 25219136
1 0x180d124 0x180d054 0
2 0x180d128 0x180d038 2
3 0x180d12c 0x180d03c 3
4 0x180d130 0x180d0b0 4
5 0x180d134 0x180d0b4 5
6 0x180d138 0x180d0b8 6
7 0x180d13c 0x180d0bc 7
8 0x180d140 0x180d140 8
9 0x180d144 0x180d144 9
Foi útil?

Solução

If you know how many insertions you will be performing, you should use reserve() on your vector accordingly. This will eliminate the need for any resizing it would otherwise perform when the capacity is exceeded.

MyVec.reserve(10);
for (int i = 0; i < 10; i++)
{
    MyVec.push_back(i);
    //...
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top