我有一个数组(例如unsigned int arr[1000])。

我想将这样的数组元素化..

arr = {4, 10, 34, 45, 6, 67, UINT_MAX, UINT_MAX .. 994 times}

那就是在我分配一些值之前,我希望数组中的默认值为UINT_MAX。

有什么办法吗?

当然for循环总是存在的,但是除此之外。

用途std::fill:

unsigned int array[5];std::fill(array, array + 5, UINT_MAX);

或std::fill_n:

unsigned int array[5];int count = 5; // - number of elements to modifyauto value = UINT_MAX; // - the value to be assigned std::fill_n(array, count, value);

或者,考虑std::array改为使用。它是C样式数组的精简包装,其中包含迭代器和size()函数等一些其他功能。而且,它不会自动衰减到指针。

请使用两阶段方法。首先,使用一个初始化器列表,然后用其余的填充std::fill

#include <limits>#include <algorithm>constexpr size_t ArraySize = 1000U;int main() {
int arr[ArraySize] = { 4,10,34,45,6,67 };

std::fill(arr + 6, arr + ArraySize, std::numeric_limits<int>::max());

return 0;}

如果要避免任何隐式或显式的make循环,则可以使用以下内容

#include <utility>#include <array>template<size_t ...ind>std::array<unsigned int, 1000> fun(std::index_sequence<ind...> ) {

return {4, 10, 34, 45, 6, 67,(ind, UINT_MAX)...};}int main(){
auto array = fun(std::make_index_sequence<994>{});}