Constant-sized vector

前端 未结 7 922
無奈伤痛
無奈伤痛 2020-12-24 02:04

Does someone know the way to define constant-sized vector?

For example, instead of defining

std::vector

it will be

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 02:23

    If you want a fixed compile-time specified size (ala std::array), but you want to be able to populate the vector with varying numbers of elements between 0 and N, then a good option is eastl::fixed_vector.

    std::vector:

    The size of a std::vector is dynamic - it will allocate required storage dynamically, and you cannot limit the size and enforce an error.

    You can however reserve a certain size, and then add elements up that size before it needs to allocate new storage.

    vector.size() is initially 0, and increases as you add elementss

    std::array:

    The size of a std::array is a compile-time constant - it will allocate required storage statically, and you cannot change the size.

    array.size() is always the size of the array, and is equal to array.max_size()

    eastl::fixed_vector:

    The size of an eastl::fixed_vector can be either static or dynamic.

    It will allocate a certain number of elements initially, and then if you allow dynamic growth, will allocate dynamically if required.

    For the purpose you originally asked for, you can disable growth (via bEnableOverflow in the template instantiation below)

    fixed_vector.size() is initially 0, and increases as you add elements.

    template::type>
    class fixed_vector;
    

    Simple example:

    #include 
    #include 
    #include 
    #include "EASTL/fixed_vector.h"
    
    int main()
    {
        std::vector v;
        v.reserve(10);
        std::cout << "size=" << v.size() << " capacity=" << v.capacity() << '\n';
    
        std::array a;
        std::cout << "size=" << a.size() << " capacity=" << a.max_size() << '\n';
    
        eastl::fixed_vector fv;
        std::cout << "size=" << fv.size() << " capacity=" << fv.capacity() << '\n';
    
        return 0;
    }
    

    Output:

    size=0 capacity=10
    size=10 capacity=10
    size=0 capacity=10
    

    Note that the size of array is 10, whereas vector and fixed_vector are 0

提交回复
热议问题