如何限制 STL vector 的 max_size?最终通过特化。欢迎举个例子。
最佳答案
做到这一点的方法是替换分配器。请注意,vector 和 string 是目前唯一实际检查其分配器 max_size 的容器。这个想法是因为这些容器保证元素存储在连续的内存中,所以容器询问分配器分配器可以处理多少元素。
这个想法
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;
};
然后制作一个新的 vector
typedef std::vector<Type,MyAllocator<Type>> vec_t;
vec_t vec(vec_t::allocator_type(4567));
我还没有尝试编译这段代码,但它应该可以工作。
关于c++ - 限制 STL 的 vector max_size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2708340/