tags:

views:

150

answers:

2

Hi

How can I limit STL vector's max_size? Eventually by specialization. An example would be welcome.

A: 

max_size in std::vector isn't something you can alter. It's a constant specific for current vector, that shows how many elements of current type you can put in that vector (I guess it will depend on your system type)

So, for std::vector<int> and std::vector<double> max_size will differ that much, as int and double differ.

Kotti
+3  A: 

The way to do this is to replace the allocator. Note that vector and string are the only containers that actually check their allocators max_size right now. The idea is that since these containers guarantee that the elements are stored in contiguous memory, the container asks the allocator just how many elements 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 make a new vector

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

I haven't tried compiling this code, but it should work.

Lance Diduck
You left out the declaration of `maxsize`. In any case, stateless allocators are better, so it should be implemented as a template parameter.
Potatoswatter
Thanks for the bug report. Virtually all std library implementation support stateful allocators, however you are right that the C++03standard does not requires this support, so making it a template woould make it strictly conformant and smaller.
Lance Diduck