如何将数组部分初始化为某个默认值?

How to intitlialize an array partially to some default value?

我有一个数组(例如,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 modify
auto value = UINT_MAX; //   -   the value to be assigned 
std::fill_n(array, count, value);

或者,考虑改用 std::array。它是 C 风格数组的薄包装器,带有一些附加功能,如迭代器和 size() 函数。此外,它不会自动衰减到指针。

扩展下面@Evg 的评论,更惯用、通用、安全和可靠的方法是使用库提供的功能:

unsigned int array[5];
// number of elements to modify
int count = std::size(array); // C++17

// the value to be assigned 
auto value = std::numeric_limits<uint32_t>::max();

std::fill_n(std::begin(array), count, value);

//OR with std::fill
std::fill(std::begin(array), std::end(array), value);

上述方法的优点是显而易见的:

  • 您只需将容器从 C 样式数组切换为 std::vectorstd::array,而无需更改上面代码中的任何其他部分。
  • 如果改变数组的大小,代码会自动适应
  • 减少人为错误的机会

请使用两阶段方法。首先,使用初始化列表,然后用 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 + 6U, arr + ArraySize, std::numeric_limits<int>::max());

    return 0;
}

以下允许您使用任何类型、大小和默认值做您想做的事:

template<typename T, size_t Size, size_t N, size_t... In, size_t... Isize>
constexpr std::array<T, Size> make_array_impl(const T(&user_supplied)[N], T default_value, std::index_sequence<In...>, std::index_sequence<Isize...>)
{
    return {user_supplied[In]..., (Isize, default_value)...};
}

template<typename T, size_t Size, size_t N>
constexpr std::array<T, Size> make_array(const T(&user_supplied)[N], T default_value)
{
    static_assert(N <= Size, "bla bla bla");
    return make_array_impl<T, Size> (user_supplied, default_value, std::make_index_sequence<N>{}, std::make_index_sequence<Size - N>{});
}

你可以这样使用它:

int main()
{
    auto arr = make_array<unsigned int, 1000>({4, 10, 34, 45, 6, 67}, UINT_MAX); // expands to arr = {4, 10, 34, 45, 6, 67, UINT_MAX... 994 times}
}

Try it on godbolt