简体   繁体   English

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

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

Is there anyway to do this? 反正有这样做吗? This is my first time using an array and its 50 elements and i know they will only get bigger. 这是我第一次使用数组及其50个元素,我知道它们只会变得更大。

Whatever kind of array you are using, if it provides iterators/pointers you can use the std::fill algorithm from the <algorithm> header. 无论使用哪种数组,如果它提供迭代器/指针,都可以使用<algorithm>标头中的std::fill算法。

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

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

(where value is the value you want to assign and elementsCount is the number of elements to modify) (其中value是要分配的值, elementsCount是要修改的元素数)

Not that implementing such a loop by hand would be so difficult... 并不是说手工实现这样的循环会如此困难...

// 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.

You can use a for loop if you must use arrays: 如果必须使用数组,则可以使用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

or as a shortcut, use std::fill 或作为快捷方式,使用std::fill

int array[50];

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

If the number you want to set all the elements to is 0 , you can do this shortcut: 如果要将所有元素设置为0 ,则可以执行以下快捷方式:

int array[50] = { };

Or if you're talking about std::vector , there is a constructor that takes the initial size of the vector and what to set each element to: 或者,如果您在谈论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