So, I have the following:
std::vector< std::vector <int> > fog;
and I am initializing it very naively like:
for(int i=0; i<A_NUMBER; i++)
{
std::vector <int> fogRow;
for(int j=0; j<OTHER_NUMBER; j++)
{
fogRow.push_back( 0 );
}
fog.push_back(fogRow);
}
And it feels very wrong... Is there another way of initializing a vector like this?
Suppose you want to initialize a two dimensional integer vector with n rows and m column each having value 'VAL'
Write it as
std::vector<vector<int>> arr(n, vector<int>(m,VAL));
This VAL can be a integer type variable or constant such as 100
There is no append
method in std::vector
, but if you want to make a vector containing A_NUMBER
vectors of int
, each of those containing other_number
zeros, then you can do this:
std::vector<std::vector<int>> fog(A_NUMBER, std::vector<int>(OTHER_NUMBER));
I think the easiest way to make it done is :
std::vector<std::vector<int>>v(10,std::vector<int>(11,100));
10 is the size of the outer or global vector, which is the main one, and 11 is the size of inner vector of type int, and initial values are initialized to 100! That's my first help on stack, i think it helps someone.
The general syntax, as depicted already is:
std::vector<std::vector<int> > v (A_NUMBER, std::vector <int> (OTHER_NUMBER, DEFAULT_VALUE))
Here, the vector 'v' can be visualised as a two dimensional array, with 'A_NUMBER' of rows, with 'OTHER_NUMBER' of columns with their initial value set to 'DEFAULT_VALUE'.
Also it can be written like this:
std::vector <int> line(OTHER_NUMBER, DEFAULT_VALUE)
std::vector<std::vector<int> > v(A_NUMBER, line)
Inputting values in a 2-D vector is similar to inputting values in a 2-D array:
for(int i = 0; i < A_NUMBER; i++) {
for(int j = 0; j < OTHER_NUMBER; j++) {
std::cin >> v[i][j]
}
}
Examples have already been stated in other answers....!
My c++ STL
code to initialise 5*3 2-D vector
with zero
#include <iostream>
using namespace std;
#include <vector>
int main()
{// if we wnt to initialise a 2 D vector with 0;
vector<vector<int>> v1(5, vector<int>(3,0));
for(int i=0;i<v1.size();i++)
{
for(int j=0;j<v1[i].size();j++)
cout<<v1[i][j]<<" ";
cout<<endl;
}
}
vector<vector<int>> board;
for(int i=0;i<m;i++) {
board.push_back({});
for(int j=0;j<n;j++) {
board[i].push_back(0);
}
}
This code snippet first inserts an empty vector at each turn, in the other nested loop it pushes the elements inside the vector created by the outer loop. Hope this solves the problem.
Let's say you want to initialize 2D vector, m*n, with initial value to be 0
we could do this
#include<iostream>
int main(){
int m = 2, n = 5;
vector<vector<int>> vec(m, vector<int> (n, 0));
return 0;
}
The recommended approach is to use fill constructor to initialize a two-dimensional vector with a given default value :
std::vector<std::vector<int>> fog(M, std::vector<int>(N, default_value));
where, M and N are dimensions for your 2D vector.
Source: Stackoverflow.com