c++vectorg++compiler-version

syntax failure with vector of vectors


I read the article Initializing a vector of vectors having a fixed size with boost assign which should exactly meet my demands: initializing a matrix-like vector of a vector that can be arbitrarily expanded in both directions (I want to use it to extract and group a selection of values out of a bigger list).

However, the solution given in the first 2 answers

    vector<vector<int>> v(10, vector<int>(10,1));        

prompts a syntax error in my CDT_eclipse and the following error from my compiler:

     error: expected identifier before numeric constant
     vector <vector <int> > v(10, vector <int>(10,1));

--

The version found in vector of vector - specific syntax works for my eclipse:

     vector<vector<int>> v = vector<vector<int>>(n, vector<int>(n, 0));        

It prompts however a warning from my compiler:

    vector warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11  [...]

Changing the compiler version (gcc 5.4.0 20160609 for Ubuntu 5.4.0-6ubuntu1~16.04.10) is not possible in the grand scheme where my code is supposed to be used. So I need a compatible formulation of the upper mentioned command. Thanks a lot!

EDIT: My two main attempts looked like this:

    vector <vector <int> > v(10, vector <int>(10,1));   --> syntax error
    vector <vector<int> > v = vector <vector<int> >(1, vector<int>(1, 0));   --> compiler error

Solution

  • I will guess here that you are forgetting to tell us that you are trying to declare a data member for a class. So you are really trying to compile something like:

    struct A {
        vector <vector <int> > v(10, vector <int>(10,1));       
    };
    

    and

    struct A {
        vector <vector<int> > v = vector <vector<int> >(1, vector<int>(1, 0));
    };
    

    A data member can only be initialized in a class definition with an equal sign or with braces. The initialization with parentheses is not allowed.

    Try:

    struct A {
        vector<vector<int>> v{10, vector<int>(10,1)};        
    };
    

    In any case you need at least C++11 for the brace-initialization, as well as non-static member initialization in the declaration (your second error where you use equals instead of parentheses, but with older C++ standard).