I am working with vector of vector and am accessing them with iterators. I wrote two simplified programs to illustrate my problem. One is with normal vectors, and the other is with vector of vector.
The first one works:
#include <iostream>
#include <vector>
typedef std::vector<double> Vec;
int main()
{
Vec v({0, 1});
std::cout << *v.begin() << " " << *(v.end()-1) << std::endl;
Vec::iterator it = v.end()-1;
v.push_back(2);
std::cout << *it << " " << *(v.end()-1) << std::endl;
return 0;
}
It outputs:
0 1
1 2
The second one looks exactly the same except v contains vectors instead of doubles.
#include <iostream>
#include <vector>
typedef std::vector<std::vector<double>> Graph;
int main()
{
Graph v({{0, 0}, {1, 1}});
std::cout << (*v.begin()).front() << " " << (*(v.end()-1)).front() << std::endl;
Graph::iterator it = v.end()-1;
v.push_back({2, 2});
std::cout << (*it).front() << " " << (*(v.end()-1)).front() << std::endl;
return 0;
}
However, it produces a segmentation fault at runtime :
0 1
Segmentation fault.
Why?