将相同的值赋给数组中所有元素的方法
A method to assign the same value to all elements in an array
我有一个包含50个元素的数组
int arr[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.
从c++ 20 ranges
使用fill
.
int arr[50];
std::ranges::fill(arr, 10);
所有50个元素的值都是10
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
}
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int