cpp initialize 2d vector code example
Example 1: initialize 2d vector of ints c++
auto M = 4;
auto N = 3;
auto default_value = 1;
std::vector<std::vector<int>> matrix(M, std::vector<int>(N, default_value));
Example 2: c++ 2D vectors
int main()
{
int row = 5;
int colom[] = { 5, 3, 4, 2, 1 };
vector<vector<int> > vec(row);
for (int i = 0; i < row; i++) {
int col;
col = colom[i];
vec[i] = vector<int>(col);
for (int j = 0; j < col; j++)
vec[i][j] = j + 1;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
}
Example 3: initialising 2d vector
vector<vector<int> > vect{ { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
Example 4: how to take input in 2d vector in c++
std::vector<vector<int>> d;
cout<<"Enter the N number of ship and port:"<<endl;
cin>>in;
cout<<"\Enter preference etc..:\n";
for(i=0; i<in; i++){
cout<<"ship"<<i+1<<":"<<' ';
for(j=0; j<in; j++){
cin>>temp;
d.push_back(temp);
}
}