My purpose is to create an adjacency list to represent a graph and i chose doing it by using vectors. My problem is that the number of vertices and edges of the graph is not always the same and it's given in input. Hence i try to declare the array of vectors dynamically. Here is my code(where N stands for the number of edges):
int N;
vector <int> *arr;
arr = new vector <int> [N];
cin >> N;`
Every time i try to handle a vector (ig arr[0].push_back(3);
) i get a segmentation fault. What am i doing wrong :(
Edit: The N stands for the number of nodes and not the edges. This does not affect the segmentation error but only the way to represent the graph with vectors
You're almost there; but you're reading N after using it. A C++ program executes line-by-line, so when it comes to new vector <int> [N]
the value N
isn't read yet! In C++ terms you're then using an uninitialized variable, which is a form of undefined behavior. In C++, unlike most other languages, it is very easy to write a meaningless program and the compiler won't stop you (although it may issue a warning - pay attention to those!).
If you move cin >> N;
to before new vector <int> [N]
then it will work better, but wait, there's a better solution...
Instead of raw arrays, it is more idiomatic to have a vector of vectors. It is safer and also easier:
std::vector<std::vector<int>> arr;
int n;
cin >> n;
arr.resize(n);
Or simply declare the vector after n
is known:
int n;
cin >> n;
std::vector<std::vector<int>> arr(n);