如何在std::list中的max_size()函数中计算最大大小

How is max size calculated in the function max_size() in std::list?

本文关键字:函数 计算 std list 中的 max size      更新时间:2023-10-16

在std::list中,如何在函数max_size()中计算最大尺寸?现在我意识到这取决于实现,但是让我们假设我是制作标准库的人。我该如何确定特定类型Tlist的最大极限它也是可移植的?

它几乎总是N的最大值,其中容器最多可以有N个元素。这通常意味着平台上的无符号整型的最大值除以容器中要存储的元素类型的大小。

这个想法是STL列表容器默认使用std::allocator作为分配器对象。并且,根据作为模板参数(type)传递的类型,std::allocator的max_size()方法将返回一个数字,该数字表示它可以分配该传递类型的最大对象数量。List应该为节点分配内存,这就是为什么你应该传递节点结构作为模板参数:

struct node {
         int data;
         node *next;
         node *prev;
      }
std::allocator<node_struct> A;
std::cout << A.max_size();

,它将打印它可以分配的最大节点数(而不是字节数)。

如何实现:

namespace test {
   template <typename T, typename A = std::allocator<T>>
   class list {
   private:
      struct node {
         T data;
         node *next;
         node *prev;
      }
      using node_allocator = typename std::allocator_traits<A>::template rebind_alloc<node>;
      node_allocator allocator;
   //...
   public:
   //...
      void max_size() { return allocator.max_size(); }
   //...
   };
}

希望有帮助!

通常是

numeric_limits<size_type>::max();

因为这是集合所施加的唯一限制,而不是平台。集合只对自己负责,所以即使它可以计算出系统的最大内存,它仍然只会返回它所施加的限制。

根据标准-这是最大可能的容器的大小。该函数必须具有恒定的复杂度。

来自当前的c++标准:

最大容器的Size_type distance(begin(), end())