Limit stl vector max_size

How can I constrain the STL vector max_size? In the end by specialization. An example would be welcome.

+2


a source to share


2 answers


The way to do this is to replace the valve. Note that vector and string are the only containers actually checking their max_size allocators right now. The idea is that because these containers ensure that the items are stored in contiguous memory, the container only asks the allocator for how many items the allocator can handle.

This is the idea

template<class T>
struct MyAllocator:std::allocator<T>
{
     template <class U> 
     struct rebind { typedef MyAllocator<U> other; };

     typedef typename std::allocator<T>::size_type size_type;

     MyAllocator(size_type sz=1234)
     : m_maxsize(sz)
     {}

     size_type max_size() const { return m_maxsize; }

  private:
     size_type m_maxsize;
};

      



then create a new vector

typedef std::vector<Type,MyAllocator<Type>> vec_t;
vec_t vec(vec_t::allocator_type(4567));

      

I have not tried compiling this code, but it should work.

+5


a source


max_size

c std::vector

is not something you can change. This is a constant specific to the current vector that shows how many elements of the current type you can fit into this vector (I think this will depend on your system type)



So, std::vector<int>

and std::vector<double>

max_size will be very different, as int

and double

different.

+1


a source







All Articles