c++ - 变长 std::array 像

标签 c++ std variable-length-array stack-allocation

由于我通常使用的 C++ 编译器允许变长数组(例如,取决于运行时大小的数组),我想知道是否有类似 std::array 的变长数组?当然 std::vector 的大小是可变的,但它在堆上分配,并在需要时重新分配。

我喜欢在运行时定义大小的堆栈分配数组。是否有任何可能具有此功能的 std 模板?也许使用具有固定最大尺寸的 std::vector

最佳答案

目前正在制定两个建议,将运行时固定大小的数组引入 C++,您可能会感兴趣:

  • Runtime-sized arrays with automatic storage duration .这将使运行时大小的数组成为一种语言特性(如在 C11 中)。所以你可以这样做:

      void foo(std::size_t size) {
        int arr[size];
      }
    
  • C++ Dynamic Arrays .这将为库带来一个新容器,std::dynarray,它在构造时被赋予固定大小。它旨在优化以尽可能在堆栈上分配。

      void foo(std::size_t size) {
        std::dynarray<int> arr(size);
      }
    

这些都是作为数组扩展技术规范的一部分进行的,该规范将与 C++14 一起发布。

更新:std::dynarray 尚未实现(2021 年 8 月 25 日)。请引用 What is the status on dynarrays?

关于c++ - 变长 std::array 像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20857577/

相关文章:

c++ - 为什么大学计算机科学类(class)推广 'using namespace std' ?

c - C 不支持可变长度数组 C99

c++ - 写入多个文件的 fclose、fopen 和 fwrite 问题

c++ - 仅移动类型的 back_inserter

c++ - std::async 导致死锁?

c++ - 为什么c++11标准库中没有std::clear

c++ - 将行编辑的输入存储到字符串 qt

c++ - 使用 pthread 处理数组/vector 的各个部分

c - C 中的静态数组

c++ - C++中使用变量初始化数组