search

Home  >  Q&A  >  body text

c++ - STL中是否有定长的数组容器,类似限制元素数目的vector,不要用c的原始数组

STL中是否有定长的数组容器,类似限制元素数目的vector,不要用c的原始数组

巴扎黑巴扎黑2806 days ago1269

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:29:23

    Generally when you need to use an array, std::vector is your first choice. It is the most efficient in most cases. If you need an array with a specified length, you can use reserve() to pre-allocate space. , or use a constructor with a length argument (number 3 in the reference). For example:

    constexpr std::size_t init_size = 100;
    
    std::vector<int> vi1(init_size);
    
    std::vector<int> vi2;
    vi2.reserve(init_size);

    Of course, there are also template classes std::array similar to the built-in compile-time determined length array.

    reply
    0
  • PHPz

    PHPz2017-04-17 13:29:23

    C++11 array.

    It is also very convenient to specify the number of elements of the vector during initialization.

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:29:23

    There is std::array, it is very useful, much easier to use than the built-in array

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:29:23

    For fixed-length arrays at compile time, std::array must be used, but I feel that the question is not referring to this, but to the variable-specified array newly introduced in C++ 17 (this feature has been available in C for a long time), and at the same time it Comes with a container std::dynarray for use with, the size is determined during the constructor and cannot then be changed. Now, you can use std::experimental::dynarray, or gsl::dyn_array.

    reply
    0
  • Cancelreply