I just don’t know how to describe this problem better. I have the following code (i wrote using namespace std to simplify it):
#include <iostream>
#include <vector>
using namespace std;
struct Vertex
{
int num;
Vertex* path;
};
int main()
{
vector<Vertex> vertexes{};
for (int i = 0; i < 2; i++)
{
vertexes.push_back({ i + 1, nullptr });
vertexes[i].path = &vertexes[i];
cout << vertexes[i].num << ": " << vertexes[i].path->num << endl;
}
cout << endl;
for (Vertex& vertex : vertexes)
{
cout << vertex.num << ": " << vertex.path->num << endl;
}
return 0;
}
The online compiler output:
1: 1
2: 2
1: 1579877676
2: 2
What am i doing wrong and where the first pointer is getting invalidated?
>Solution :
https://en.cppreference.com/w/cpp/container/vector/push_back
If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
Your code doesn’t check whether this is happening, but it’s likely that it happens on the second push_back, in which case the pointer (iterator) to vertexes[0] may be invalidated.
If you want this to work then you can use reserve to increase the capacity to a sufficiently large value before you start. Or use a different container such as list.