Reputation: 135
How can I create an NxM 2D int vector and create default values for it?
Here I try to create a 3x3 int vector with some values:
vector< vector<int> > m(3, vector<int> (3)) = {
{1,2,9},
{8,4,7},
{5,6,0}
};
But this errors with
> g++ a.cpp -std=c++11
error: expected ‘,’ or ‘;’ before ‘=’ token
vector< vector<int> > m(3, vector<int> (3)) = {
^
error: expected ‘}’ at end of input
}
I am using c++11 also, so shouldn't the above syntax be correct? According to this answer, it should be okay?
Upvotes: 0
Views: 1364
Reputation: 44878
The code in parentheses provides arguments for vector
's constructor:
vector<vector<int>>(3, vector<int>(3));
This creates a new vector that contains three elements of type vector
, and each of them has got three integers inside. So, no null
s inside a vector in this case.
This code:
vector<vector<int>> test =
{ {3,4,5},
{4,5,6} };
Uses another constructor, which takes an initializer list and deduces the size of the resulting vector by itself.
Those are different constructors! When you construct an object with the Type object(arg1, arg2);
notation, you're basically calling the constructor of Type
. You're calling a function, and of course you cannot adding to a function call.
Upvotes: 0
Reputation: 29022
It works fine if you remove what's in the parenthesis. The dimensions are determined by the size of the initializer lists. If you want to specify the size yourself, you can use std::array
.
std::vector< std::vector<int> > m= {
{1,2,9},
{8,4,7},
{5,6,0}
};
Initializing arrays is a bit different. See this question. You need double braces.
#include <array>
std::array< std::array<int, 3>, 3 > m= {{
{1,2,9},
{8,4,7},
{5,6,0}
}};
Upvotes: 1