std::vector<T,Allocator>::capacity
来自 cppreference.com
size_type capacity() const; |
(自 C++11 起 noexcept) (自 C++20 起 constexpr) |
|
返回容器当前已分配的空间大小。
内容 |
[编辑] 参数
(无)
[编辑] 返回值
当前已分配存储的容量。
[编辑] 复杂度
常量。
[编辑] 示例
运行此代码
#include <iomanip> #include <iostream> #include <vector> int main() { int sz = 100; std::vector<int> v; auto cap = v.capacity(); std::cout << "Initial size: " << v.size() << ", capacity: " << cap << '\n'; std::cout << "\nDemonstrate the capacity's growth policy." "\nSize: Capacity: Ratio:\n" << std::left; while (sz-- > 0) { v.push_back(sz); if (cap != v.capacity()) { std::cout << std::setw( 7) << v.size() << std::setw(11) << v.capacity() << std::setw(10) << v.capacity() / static_cast<float>(cap) << '\n'; cap = v.capacity(); } } std::cout << "\nFinal size: " << v.size() << ", capacity: " << v.capacity() << '\n'; }
可能输出
Initial size: 0, capacity: 0 Demonstrate the capacity's growth policy. Size: Capacity: Ratio: 1 1 inf 2 2 2 3 4 2 5 8 2 9 16 2 17 32 2 33 64 2 65 128 2 Final size: 100, capacity: 128
[编辑] 另请参阅
返回元素数量 (公有成员函数) | |
保留存储空间 (公有成员函数) |