Home > other >  How to declare 2D vector of strings in c with size
How to declare 2D vector of strings in c with size

Time:06-08

vector board(n, string(n, '.')); Is this is the way to declare 2d vector of strings ??

CodePudding user response:

It's a 1d vector of strings, which in a sense can be considered as a 2d data structure of chars (containing n * n dots). By the way, you probably should write vector<string>, not just vector, to get your definition compiled.

If you really want a 2d data structure of strings, you need to write

vector<vector<string>> board(n, vector<string>(n, string(n, '.')));

This code actually creates a 3d data structure containing n * n * n dots.

CodePudding user response:

#include <iostream>
#include<vector>

using namespace std;

int main()
{
 vector<string> board(4, string(4, '.'));
 
 for(int i=0; i<board.size(); i  ){
     cout<<board[i]<<endl;
 }
    return 0;
}

OUTPUT

....

....

....

....

so this is like - ['....', '....','....','....'] since it's a string, it feels like a 2D vector, but it isnt. Here board[0]= '....' and since its a string so board[0][0] = '.'

but if u define like this :

vector<vector<string>> board(4, vector<string>(4, "."));

board will be equal to : [['.', '.', '.', '.'], ['.', '.', '.', '.'],['.', '.', '.', '.'],['.', '.', '.', '.'],['.', '.', '.', '.']] surely a 2D vector.

Here board[0] = ['.', '.', '.', '.'] and board[0][0] = '.'

Also Good Luck With N-Queen Problem in Leetcode!

  • Related