Constant-sized vector

If you want a fixed compile-time specified size (ala std::array<T, N>), 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<typename T, 
         size_t nodeCount, 
         bool bEnableOverflow = true, 
         typename OverflowAllocator = 
                      typename eastl::type_select<bEnableOverflow,
                                                  EASTLAllocatorType, 
                                                  EASTLDummyAllocatorType>::type>
class fixed_vector;

Simple example:

#include <iostream>
#include <vector>
#include <array>
#include "EASTL/fixed_vector.h"

int main()
{
    std::vector<int> v;
    v.reserve(10);
    std::cout << "size=" << v.size() << " capacity=" << v.capacity() << '\n';

    std::array<int, 10> a;
    std::cout << "size=" << a.size() << " capacity=" << a.max_size() << '\n';

    eastl::fixed_vector<int, 10, false> 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


There is no way to define a constant size vector. If you know the size at compile time, you could use C++11's std::array aggregate.

#include <array>

std::array<int, 10> a;

If you don't have the relevant C++11 support, you could use the TR1 version:

#include <tr1/array>

std::tr1::array<int, 10> a;

or boost::array, as has been suggested in other answers.


The std::vector can always grow dynamically, but there are two ways you can allocate an initial size:

This allocates initial size and fills the elements with zeroes:

std::vector<int> v(10);
v.size(); //returns 10

This allocates an initial size but does not populate the array with zeroes:

std::vector<int> v;
v.reserve(10);
v.size(); //returns 0

Tags:

C++

Stl

Vector