Reputation: 4273
How can I initialize an array of vectors properly ?
Graph.h
class Graph
{
public:
Graph(int vertices);
private:
vector<int> adjacencyLists[];
}
Graph.cpp
Graph::Graph(int vertices)
{
adjacencyLists = new vector<int>[vertices];
}
Error:
error: incompatible types in assignment of 'std::vector<int>*' to 'std::vector<int> [0]'
adjacencyLists = new vector<int>[vertices];
^
Upvotes: 0
Views: 310
Reputation: 28168
The perfect thing to you for your use case (a dynamically allocated array which can't change size after construction) is std::dynarray
. Sadly, this is currently not in the standard. Here's how it would work:
dynarray<vector<int>> adjacencyLists;
Graph::Graph(int vertices) : adjacencyLists{vertices} {}
Since it's not in the standard yet, I'd go with a vector
(which is really a superset of dynarray
, so its use is literally identical):
vector<vector<int>> adjacencyLists;
Graph::Graph(int vertices) : adjacencyLists{vertices} {}
Or if you really want to manage it all yourself, you could store it in a unique_ptr
:
unique_ptr<vector<int>[]> adjacencyLists;
int numVertices;
Graph::Graph(int vertices)
: adjacencyLists{new vector<int>[vertices]}
, numVertices{vertices}
{}
With this approach you almost definitely want to store the size of adjacencyLists
as well (as shown above), otherwise you won't be able to iterate through the array as you won't know how big it is.
No matter what you do, never have a raw pointer own memory. It should always be a unique_ptr
, shared_ptr
or some container. If you use the delete
keyword, it's not modern c++.
Upvotes: 2
Reputation:
Change:
vector<int> adjacencyLists[];
To:
vector<int>* adjacencyLists;
Upvotes: 1