1

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?

jww
  • 97,681
  • 90
  • 411
  • 885
Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • Do you know how many values you're going to add, or can it keep increasing over the life of the program? – Tas Sep 17 '18 at 03:47
  • 4
    Possible duplicate of [Avoid the reallocation of a vector when its dimension has to be incremented](https://stackoverflow.com/q/44332477/608639). About the best you can do is call reserve to allocate for the expected number of elements in advance. If you don't know how many that is, then pick an arbitrarily large number like 4 million. 4M is small enough that it should not cause problems for a modern desktop. – jww Sep 17 '18 at 04:34
  • 1
    The best solution is to not write code that depends on the address. – molbdnilo Sep 17 '18 at 05:19
  • @molbdnilo: The problem is that there's a large body of C code that expects a `T*` pointing to `N` elements. `std::vector(N)` is intentionally contiguous to support that use case. – MSalters Sep 17 '18 at 11:03
  • I just figured out using `std::deque` instead of `std::vector` simply solves the problem. I hope it's safe though. – Zack Lee Dec 17 '18 at 04:35

2 Answers2

2

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

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

std::vector<int> vec;
vec.reserve(5);
for (int i = 0; i < 5; ++i)
...
songyuanyao
  • 169,198
  • 16
  • 310
  • 405