variable-length std::array like

后端 未结 2 407
野性不改
野性不改 2020-12-30 00:54

As my usually used C++ compilers allow variable-length arrays (eg. arrays depending on runtime size), I wonder if there is something like std::array with variab

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 01:30

    As Daniel stated in the comment, size of the std::array is specified as a template parameter, so it cannot be set during runtime.

    You can though construct std::vector by passing the minimum capacity through the constructor parameter:

    #include 
    
    int main(int argc, char * argv[])
    {
        std::vector a;
        a.reserve(5);
        std::cout << a.capacity() << "\n";
        std::cout << a.size();
    
        getchar();
    }
    

    But. Still vector's contents will be stored on the heap, not on the stack. The problem is, that compiler has to know, how much space should be allocated for the function prior to its execution, so it is simply not possible to store variable-length data on the stack.

提交回复
热议问题