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?