3

Im currently doing a programming project, and I've come across a problem while compiling... I have this code made in C++:

scanf("%d %d", &number, &shares);
vector<int> graph[number];

I read the variable number, and use it to initialise the size of the array. But this produces a initialising problem,

variable length array of non-POD element type vector<int>

Anyone knows what I can do to solve this?

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324

3 Answers3

4

You are attempting to define an array of vectors, but arrays cannot have runtime determined sizes. Presumably, you want to declare a vector of a certain type, which you can do like this:

vector<int> graph(number); // vector of size = number

Edit: After your comments, it seems that what you're after is a vector of vectors:

vector<vector<int>> graph(number);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

Check this related posts, as they have this same problem as yours:

Community
  • 1
  • 1
-2

You're trying to create an array of vectors, which is not a good thing if you don't do this through dynamic allocation. If you want an array of vectors, do this:

vector<int> * graph = new vector<int>[number];
...
delete[] graph;

If you want to have a vector of size number, then do this:

vector<int> graph(number);
mcopik
  • 341
  • 2
  • 6
  • Thanks, it's the first one you inputed! I have to do an implementation of Tarjan's algorithm, and to store the graph, I mean to use a number of nodes read from input, and then store in a vector in each position all of the outgoing connections of each node. I only meant to use the multidimensional array this way because I could initialise the array in the specific number of nodes that I read from input! Still, I will try this right away! Thank you! – FranciscoTSilva Mar 15 '14 at 22:39
  • Instead of this, do vector> graph(number); – M.M Mar 15 '14 at 23:21