【发布时间】:2011-12-07 20:10:15
【问题描述】:
我有一个包含 50 个元素的数组
int arr[50];
我想将所有元素设置为相同的值。我该怎么做?
【问题讨论】:
-
数组是指
std::vector? -
请显示一些代码。目前我们不知道您所说的 array 是什么意思,它可能是
std::vector、std::array、char[50]等。
我有一个包含 50 个元素的数组
int arr[50];
我想将所有元素设置为相同的值。我该怎么做?
【问题讨论】:
std::vector?
std::vector、std::array、char[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::fill 允许灵活地为元素范围分配值。
使用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<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
}
【讨论】: