vector::capacity

本文详细解释了C++标准模板库(STL)中vector容器的容量(capacity)概念,区分了容量与大小的区别,并通过示例代码展示了如何使用size(), capacity()和max_size()三个成员函数来获取vector对象的当前大小、分配的容量以及最大可能的尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vector::capacity(容量)

Return size of allocated storage capacity
Returns the size of the storage space currently allocated for the vector, expressed in terms of elements.

This capacity is not necessarily equal to the vector size. It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.

Notice that this capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container (reallocating it storage space). The theoretical limit on the size of a vector is given by member max_size.

The capacity of a vector can be explicitly altered by calling member vector::reserve.

Parameters

none

Return Value

The size of the currently allocated storage capacity in the vector, measured in terms of the number elements it can hold.

Member type size_type is an unsigned integral type.

capacity的意思是容量,此方法返回的是该vector对象最多能容纳多少个元素。
size的意思是大小,此方法是返回该vector对象当前有多少个元素。
// comparing size, capacity and max_size
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
  std::vector<int> myvector;

  // set some content in the vector:
  for (int i=0; i<100; i++) myvector.push_back(i);

  cout << "size: " << (int) myvector.size() << '\n';
  cout << "capacity: " << (int) myvector.capacity() << '\n';
  cout << "max_size: " << (int) myvector.max_size() << '\n';
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值