limit stl's vector max_size
How can I limit STL vector's max_size? Eventually by specialization. An example would be wel开发者_如何学JAVAcome.
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.
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.
精彩评论