2d vecotr code example

Example 1: 2d vector

#include <bits/stdc++.h>
using namespace std;
int main() 
{
  int rows = 2;
  int cols = 2;
  int val = 1;
  vector< vector<int> > v(rows, vector<int> (cols, val));  /*creates 2d vector “v[rows][cols]” and initializes all elements to “val == 1” (default value is 0)*/
  v[0][0] = 5;
  v[1][1] = 4;
  cout << v[0][0] << endl; //Output: 5cout << v[1][0] << endl; //Output: 1return 0;}

Example 2: c++ 2D vectors

int main() 
{ 
    int row = 5; // size of row 
    int colom[] = { 5, 3, 4, 2, 1 }; 
  
    vector<vector<int> > vec(row);  // Create a vector of vector with size equal to row. 
  	for (int i = 0; i < row; i++) { 
  		int col;  
        col = colom[i]; 
  		vec[i] = vector<int>(col); //Assigning the coloumn size of vector
        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: 2d vector

#include <bits/stdc++.h>
using namespace std;
main() {
	int r=2,c=3,val=1;
	vector<vector<int>> v(r,vector<int>(c,val)); 
	/*
    2d vector “v[r][c]”;
    all elements = val; 
    (default value is 0)
    */
	for(int i=0;i<r;i++) 
		for(int j=0;j<c;j++) 
  			cout<<v[i][j]<<" ";
        cout<<endl;
  	/*
    1 1 1
    1 1 1
    */
}

Example 4: 2d vector

vector<vector<int>> v(row,vector<int>(col,val));

Tags:

Cpp Example