How to prevent vector from memory address change

3128 views c++
9

I would like to know if there's any good solution to prevent vector from memory address change.

My Code :

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec;

    for (int i = 0; i < 5; ++i)
    {
        vec.push_back(i);

        std::cout << "----------Current memory addresses----------\n";
        for (size_t j = 0; j < vec.size(); ++j)
            std::cout << j << " : " << &vec[j] << '\n';
    }
    return 0;
}

The Result :

----------Current memory addresses----------
0 : 0x10060b970
----------Current memory addresses----------
0 : 0x1006089a0
1 : 0x1006089a4
----------Current memory addresses----------
0 : 0x10060b970
1 : 0x10060b974
2 : 0x10060b978
----------Current memory addresses----------
0 : 0x10060b970
1 : 0x10060b974
2 : 0x10060b978
3 : 0x10060b97c
----------Current memory addresses----------
0 : 0x100611e40
1 : 0x100611e44
2 : 0x100611e48
3 : 0x100611e4c
4 : 0x100611e50
Program ended with exit code: 0

As you can see, the memory address changes as soon as I push_back() a new value into the vector.

Is there any good solution to make addresses not change?

answered question

Do you know how many values you're going to add, or can it keep increasing over the life of the program?

2 Answers

11

You can use std::vector::reserve to avoid reallocation.

std::vector<int> vec;
vec.reserve(5);
for (int i = 0; i < 5; ++i)
...

posted this
10

You can reserve memory for the required number of elements first.

std::vector<int> vec;

// Reserve memory for 5 elements
vec.reserve(5); 

for (int i = 0; i < 5; ++i)
{
    vec.push_back(i);

    ...
}

See the documentation of std::vector::reserve for additional info.

posted this

Have an answer?

JD

Please login first before posting an answer.