Search code examples
c++vectorfillmemset

using std::fill on a 2D int vector


I am trying to set the values of all elements in 2D vector to a particular value. As far as I am aware of, one cannot use memset for vectors like how they are used for arrays. Hence I have to use std::fill to set all elements in 2D vector to a particular value. However, I am aware of how to use fill for a 1D vector as show below.

vector<int> linearVector (1000,0);
fill(linearVector.begin(),linearVector.end(),10);

However, when I try to do something similar for a 2D vector(as shown below) it does not work.

vector<vector<int> > twoDVector (100,vector <int> (100,0));
fill(twoDVector.begin(),twoDVector.end(),10);

PS: I am aware that I can easily design a nested for loop to manually set the elements of the 2D vector to the value I want. However, It is not feasible in my program as the size of the 2D vector is quite large and there are other time consuming functions(recursive functions) happening in parallel.


Solution

  • You could use like this:

    fill(twoDVector.begin(), twoDVector.end(), vector<int>(100, 10));