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

How to intitlialize an array partially to some default value?

本文关键字:默认值 初始化 数组部      更新时间:2023-10-16

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

我想灌输像这样的数组的元素..

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

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

有什么办法可以做到这一点吗?

当然,for 循环总是存在的,但除此之外,任何其他方式。

请使用 2 阶段方法。首先,使用初始化器列表,然后用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}
}

在神螺栓上尝试一下

使用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,则无需更改上述代码中的任何其他部分。
  • 如果更改数组的大小,代码将自动适应
  • 减少人为错误的可能性