限制stl的向量max_size

时间:2010-04-25 13:14:35

标签: c++ stl

如何限制STL向量的max_size?最终通过专业化。一个例子是受欢迎的。

2 个答案:

答案 0 :(得分:5)

执行此操作的方法是替换分配器。请注意,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;
};

然后制作一个新的载体

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

我还没有尝试过编译这段代码,但它应该可以正常工作。

答案 1 :(得分:1)

max_size中的{p> std::vector不是您可以改变的。它是当前向量的常量,它显示了可以在该向量中放置的当前类型的元素数量(我猜它将取决于您的系统类型)

因此,对于std::vector<int>std::vector<double>,max_size差异很大,因为intdouble不同。

相关问题