capacity函数
语法:
1 |
size_type capacity() const; |
capacity() 返回vector所能容纳的元素数量(在不重新分配内存的情况下)
源代码
1 2 3 4 5 6 7 |
/** * Returns the total number of elements that the %vector can * hold before needing to allocate more memory. */ size_type capacity() const { return size_type(const_iterator(this->_M_impl._M_end_of_storage) - begin()); } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1(100, 0); vector<int> v2(10, 2); cout<< "v1向量元素个数" << v1.size() <<endl; cout<< "v1向量容量" << v1.capacity() <<endl; v2.push_back(121); cout<< "v2向量元素个数" << v2.size() <<endl; cout<< "v2向量容量" << v2.capacity() <<endl; } |
测试结果:
1 2 3 4 |
v1向量元素个数100 v1向量容量100 v2向量元素个数11 v2向量容量20 |
注:元素个数理论所占容量都会小于容器申请内存的容量,这个也很好理解,比如将鸡蛋放篮子里,最多只能放满,再放的话就要拿一个更大的篮子。