限制 stl 的向量 max_size

发布于 2024-08-29 19:52:15 字数 41 浏览 2 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

琉璃梦幻 2024-09-05 19:52:16

实现这一点的方法是替换分配器。请注意,向量和字符串是目前唯一实际检查其分配器 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));

我还没有尝试编译此代码,但它应该可以工作。

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.

冷︶言冷语的世界 2024-09-05 19:52:16

std::vector 中的 max_size 不是您可以更改的内容。它是特定于当前向量的常量,显示您可以在该向量中放入多少当前类型的元素(我猜这将取决于您的系统类型)

因此,对于 std::vector和 std::vectormax_size 会有很大差异,就像 intdouble 不同一样。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文