c++arraysvector

C++ alternatives to std::array when the size is fixed, but not a constexpr?


What is the best replacement for std::array<...> if I don't want to have to provide constexpr size? I figured it would be best to just use std::vector and do reserve(...) on it, but maybe I'm overlooking something?


Solution

  • Yes, use std::vector.

    So if your code is

    std:array<int, 42> my_array;
    

    Replace it by

    std:vector<int> my_array(42);
    

    Note: you probably don't want to use reserve, because it leaves the vector empty. If you are using std::array, your code doesn't have the concept of empty array, so it's best represented by a std::vector instance that is filled at construction, and never resized.