Amith Kotian
Amith Kotian

Reputation: 440

To initialize 2D vector with zero values

I want to construct an 2D-array of value passed n, basically I am trying construct n*n array and want to assign all values to zero. to do that vector<vector<int> > ans(n, vector<int>(n)); I am trying like this but when check for the size it is returning value of n passed. where i am expecting the array size to be n*n

Is it right way to do like this? is there better way to do it.

   int n = 3;
   vector<vector<int> > ans(n, vector<int>(n));//initialize
   cout<<"size before :"<<ans.size()<<endl;

Upvotes: 1

Views: 3861

Answers (2)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14589

You might like an idea to create own container class, which may or may not use std::vector as a storage. and would emulate 2D-array using vector or dynamically allocated 1D array. That way you would have a contiguous sequence of elements, you may treat the data as 1D array when required without taunting UB, etc. Such containers actually exist for this purpose in a number of libraries, e.g. Matrix class with Dynamic size in Eigen

Upvotes: 2

kadina
kadina

Reputation: 5376

vector<vector<int> > ans(n, vector<int>(n));

It means you are specifying 'ans' as a vector of size 'n' where each element is a vector of ints. So when you use size(), it will return 'n' only because 'ans' has only 'n' elements. It won't return n * n.

Upvotes: 2

Related Questions