c++ - 如何获取 constexpr 变量作为声明(内置)数组的维度?

标签 c++ arrays vector initialization constexpr

我在想象以下场景: 从一个空 vector 开始,将一些整数压入其中,然后使用它的大小来声明一个内置数组。

  vector<int> vec;      /* default init'ed */

  for(decltype(vec.size()) i = 0; i != 10; ++i){
    vec.push_back(i);
  }


  constexpr size_t sz = vec.size();
  int arr[sz] = {};     /* list init, left out elem's are 0 */

这个过程对我来说很直观(作为初学者)。但它失败并显示以下消息:

testconstexpr2.cpp:22:34: error: call to non-constexpr function ‘std::vector<_Tp, _Alloc>::size_type std::vector<_Tp, _Alloc>::size() const [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
testconstexpr2.cpp:23:13: error: size of array ‘arr’ is not an integral constant-expression

在使用 std::array 或动态数组分配等变通方法之前,我宁愿坚持使用内置数组。

最佳答案

这行不通,因为 vec.size() 不是 constexpr 函数,并且数组维度必须是编译时常量表达式。

在 C++1y/C++14 开发期间(未完全完成)有一个名为 std::dynarray 的提案允许你这样做,但它被放弃了,也许是将在下一个 C++1z/C++17 开发期间重新启动。

你能做的是

constexpr size_t sz = 10; /* or any other integral constant expression */
int arr[sz] = {};

关于c++ - 如何获取 constexpr 变量作为声明(内置)数组的维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24563206/

相关文章:

c++ - 栈帧问题 : Java vs C++

c++ - 启用 istream operator>> 接受两个或三个值

c++ - 无法获得 vector 中元素的总和

javascript - 根据circle1的速度计算两个圆接触的点

java - ArrayList vs Vector - 除了线程安全和性能之外的其他优势?

c++ - 为什么更新 dll 需要重新编译,有时则不需要?

c++ - 无法使用 winapi 获取资源位图大小

java - int数组内容右移到num

javascript - 如何获取对象数组中键的总和并删除连续对象的重复项?

python - (python) 如果条件成立,则在连续行中添加元素