如何在C++中用索引优雅初始化数组元素?是否有标准库函数?
用索引自动初始化C++数组的优雅方案
标准库原生实现(C++14及以上)
C++14引入的std::index_sequence可以帮我们生成编译期整数序列,结合std::array就能实现自动用索引初始化数组,完全不需要手动写初始化列表:
#include <array> #include <utility> struct MyObject { size_t mMyIndex; MyObject(size_t myIndex) : mMyIndex(myIndex) {} }; // 利用索引序列展开生成元素 template <size_t N, size_t... Is> constexpr std::array<MyObject, N> create_indexed_array(std::index_sequence<Is...>) { return {{MyObject(Is)...}}; } // 对外暴露的初始化函数 template <size_t N> constexpr std::array<MyObject, N> initialize_array_with_indices() { return create_indexed_array<N>(std::make_index_sequence<N>()); } // 使用示例 static constexpr size_t ELEMENT_COUNT = 8; constexpr auto mObjects = initialize_array_with_indices<ELEMENT_COUNT>();
这个方案是编译期完成初始化,效率拉满,修改ELEMENT_COUNT时不需要做任何额外调整,哪怕是1000这样的大数也能轻松处理。
兼容C++11的降级方案
如果你的环境不支持C++14,可以手动实现一个简单的整数序列生成器,核心逻辑和上面一致:
#include <array> // 手动实现索引序列生成 template <size_t... Is> struct index_sequence {}; template <size_t N, size_t... Is> struct make_index_sequence : make_index_sequence<N-1, N-1, Is...> {}; template <size_t... Is> struct make_index_sequence<0, Is...> : index_sequence<Is...> {}; struct MyObject { size_t mMyIndex; MyObject(size_t myIndex) : mMyIndex(myIndex) {} }; template <size_t N, size_t... Is> constexpr std::array<MyObject, N> create_indexed_array(index_sequence<Is...>) { return {{MyObject(Is)...}}; } template <size_t N> constexpr std::array<MyObject, N> initialize_array_with_indices() { return create_indexed_array<N>(make_index_sequence<N>()); } // 使用示例 static constexpr size_t ELEMENT_COUNT = 1000; constexpr auto mObjects = initialize_array_with_indices<ELEMENT_COUNT>();
关于原生数组 vs std::array
原生数组在C++17之前无法直接作为函数返回值,语法限制较多;std::array兼具原生数组的性能和标准容器的便利性(支持迭代器、拷贝、编译期操作等),是更推荐的选择。
标准库是否有现成函数?
标准库中没有直接提供initialize_array_with_indices<N>()这类封装好的函数,但基于std::index_sequence的实现非常轻量,完全符合C++标准规范。
内容的提问来源于stack exchange,提问作者tenfour
相关产品推荐
相关产品推荐

