0
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.

7
  • 5
    vector<vector<int>> is much better Commented Jul 1, 2016 at 6:20
  • 3
    The declaration vector<int > a[]; is not valid C++. Commented Jul 1, 2016 at 6:25
  • @Cheersandhth.-Alf Actually it is in some context, but in this case it declares a variable of "an incomplete object type". Commented Jul 1, 2016 at 6:33
  • @Holt: It's good to be aware of contexts, but in your answer you write "you cannot declare object of incomplete type", which isn't sufficiently context-qualified for the most pedantic, I think. :) Commented Jul 1, 2016 at 6:52
  • @Cheersandhth.-Alf I am not aware of context where it is allowed to define object with incomplete type - Are there any? The goal of my note was to point out that this is not a valid declaration in this context (there may be context where it is, but I am not going to list them, it would be useless here... ) and to explain why it compiles on gcc (and thus why it raises an error when assigning from new ...). Commented Jul 1, 2016 at 6:59

1 Answer 1

2

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].

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.