将原始数组初始化为一个值 [英] Initializing Primitive Array to One Value
本文介绍了将原始数组初始化为一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法初始化一个基本数组,比如一个整数数组,到0?不使用for循环?寻找不涉及for循环的简明代码。
Is there a way to initialize an array of primitives, say a integer array, to 0? Without using a for loop? Looking for concise code that doesn't involve a for loop.
:)
推荐答案
int array[10] = {}; // to 0
std::fill(array, array + 10, x); // to x
请注意,通用方式结束:
Note if you want a more generic way to get the end:
template <typename T, size_t N>
T* endof(T (&pArray)[N])
{
return &pArray[0] + N;
}
获取:
std::fill(array, endof(array), x); // to x (no explicit size)
应该提到 std :: fill
只是一个包装你想要避免的循环, = {};
可以用这样的术语来实现。
It should be mentioned std::fill
is just a wrapper around the loop you're trying to avoid, and = {};
might be implemented in such terms.
这篇关于将原始数组初始化为一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文