这似乎需要一个更新的答案。
建议使用标准的 alogos,而不是使用手写循环。在这种情况下iota
,正是需要的:自动递增分配。
对于静态数组,我们也应该使用 std::array 而不是 'C' 样式的数组。但这对向量也适用,因为 iota 需要运行时参数。
template<size_t SZ>
auto<int, SZ> CountInit()
{
std::array<int, SZ> arr; // Note we only use SZ once
std::iota(arr.begin(), arr.end(), 0);
return arr;
}
这可以使用 integer_sequence 和一些帮助程序以更多的编译时间方式完成:
// Note taken from : https://jgreitemann.github.io/2018/09/15/variadic-expansion-in-aggregate-initialization/
template <typename Container, int... I>
Container iota_impl(std::integer_sequence<int, I...>) {
return {I...};
}
template <typename T, std::size_t N>
auto iota_array() {
using Sequence = std::make_integer_sequence<int, N>;
return iota_impl<std::array<T, N>>(Sequence{});
}
auto foo2()
{
return iota_array<int, 10>();
}
int goo2()
{
auto x=foo2();
return std::accumulate(x.begin(), x.end(), 0);
}
根据https://godbolt.org/z/59hqqdEYj这些是等价的(根据 c++20 iota 是 constexpr)