I have a problem with this code. I try to create a struct "point" in which there is a vector of the same struct. If N is small (1,2,3) there aren't problems and the program is correctly execute, while if N is enough big (10..100) the compiler return this error:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
I have seen this topic How to create a structure which contains a list of itself? and it says that is legal put inside a struct a vector that refers to that struct. Help is greatly appreciated. Thanks!
#include <iostream>
#include <vector>
using namespace std;
struct point{
int a;
int b;
vector<point> near;
};
int main()
{
int N = 100;
vector<vector<point>> a;
a.resize(N);
for ( int i = 0; i<N; i++){
a[i].resize(N);
}
for ( int i = 0; i<N; i++){
for ( int j=0; j<N; j++){
a[i][j].near.reserve(4);
if ( i+1< N) {a[i][j].near.push_back(a[i+1][j]);}
if ( i-1>=0) {a[i][j].near.push_back(a[i-1][j]);}
if ( j+1< N) {a[i][j].near.push_back(a[i][j+1]);}
if ( j-1>=0) {a[i][j].near.push_back(a[i][j-1]);}
}
}
return 0;
}
Windows 10 - Code::blocks 16.01.