Reputation: 3
class graph
{
vector<int > a[];
int nodes,edges;
public:
graph(int n,int m)
{
nodes=n;edges=m;
a = new vector<int> [n];
}
};
This is a snippet from my code. How do I resize the array
of vector<int>
? I tried to dynamically assign the size. But its giving error.
Upvotes: 0
Views: 1326
Reputation: 37606
Use std::vector<std::vector<...>>
instead of a "raw" array of std::vector<...>
and then use .resize()
:
std::vector<std::vector<int>> a;
a.resize(n);
This will save you from having to write a lots of boilerplate code (custom destructor, copy-constructor, ...), and will be much less error prone than your actual code.
The actual problem in your code is that vector<int> a[]
should not be valid in this context: it declares a variable a
of "derived-declarator-type-list array of unknown bound of int”, which is "an incomplete object type", and you cannot declare object of incomplete type. On gcc, if you add -pedantic
, you will get a warning:
warning: ISO C++ forbids zero-size array 'a' [-Wpedantic]
But without -pedantic
, it declares a std::vector<int> a[0]
, which cannot be assigned a std::vector<int> *
and it is why you get an error when assigning new std::vector<int> [n]
.
Upvotes: 2