如何在std::list中的max_size()函数中计算最大大小
How is max size calculated in the function max_size() in std::list?
在std::list中,如何在函数max_size()中计算最大尺寸?现在我意识到这取决于实现,但是让我们假设我是制作标准库的人。我该如何确定特定类型T
的list
的最大极限它也是可移植的?
它几乎总是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++标准:
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 函数计算用户按下按钮的频率
- C++ 在编译时具有函数计算全局变量
- C++ - 使用特定函数计算 x 和 y 的最终值
- 尝试使用函数计算有剩余球员的球队数量
- 我正在尝试创建一个布尔函数,该函数计算字符并在字符为"()*-+"时返回 true
- 哈希函数计算
- 为什么 if 语句对于运算符重载函数计算 false
- 使用C 中的内在函数计算相交
- 如何使用 2 个迭代器进行求和函数计算映射<字符串、双精度>
- vector.size() 函数计算量大吗?
- 如何使用opencv函数计算图像的孔数(二进制)
- 斐波那契函数计算不正确
- 如何用3个用户定义的函数计算一个数字的真平方根
- 元函数计算 x^n 并返回整数限制而不溢出(如果不可能)
- 使用递归函数计算字符串中的元音
- 如何使用 pow() 函数计算 C++ 中超过 2^32 的幂
- 返回 void 的函数的无序函数计算
- 在 C++ 中使用尾递归函数计算列表的总和
- 使用结构和函数计算线的长度