在2D int向量上使用std :: fill [英] using std::fill on a 2D int vector
问题描述
我正在尝试将2D矢量中所有元素的值设置为特定值.据我所知,不能将memset用于向量,例如如何将它们用于数组.因此,我必须使用std :: fill将2D向量中的所有元素设置为特定值.但是,我知道如何对一维矢量使用填充,如下所示.
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);
但是,当我尝试对2D向量执行类似操作时(如下所示),它不起作用.
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:我知道我可以轻松设计一个嵌套的for循环,以将2D向量的元素手动设置为所需的值.但是,在我的程序中这是不可行的,因为2D向量的大小很大,并且还有其他耗时的函数(递归函数)并行发生.
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.
推荐答案
您可以这样使用:
fill(twoDVector.begin(), twoDVector.end(), vector<int>(100, 10));
这篇关于在2D int向量上使用std :: fill的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!