繁体   English   中英

为数组中的所有元素分配相同值的方法

[英]A method to assign the same value to all elements in an array

反正有这样做吗? 这是我第一次使用数组及其50个元素,我知道它们只会变得更大。

无论使用哪种数组,如果它提供迭代器/指针,都可以使用<algorithm>标头中的std::fill算法。

// STL-like container:
std::fill(vect.begin(), vect.end(), value);

// C-style array:
std::fill(arr, arr+elementsCount, value);

(其中value是要分配的值, elementsCount是要修改的元素数)

并不是说手工实现这样的循环会如此困难...

// Works for indexable containers
for(size_t i = 0; i<elementsCount; ++i)
    arr[i]=value;

使用std::vector

std::vector<int> vect(1000, 3); // initialize with 1000 elements set to the value 3.

如果必须使用数组,则可以使用for循环:

int array[50];

for (int i = 0; i < 50; ++i)
    array[i] = number; // where "number" is the number you want to set all the elements to

或作为快捷方式,使用std::fill

int array[50];

std::fill(array, array + 50, number);

如果要将所有元素设置为0 ,则可以执行以下快捷方式:

int array[50] = { };

或者,如果您在谈论std::vector ,则有一个构造函数,该构造函数采用vector的初始大小以及将每个元素设置为以下内容的方式:

vector<int> v(50, n); // where "n" is the number to set all the elements to.
for(int i=0;i<sizeofarray;i++)
array[i]=valuetoassign

using method


void func_init_array(int arg[], int length) {
  for (int n=0; n<length; n++)
   arg[n]=notoassign
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM