vector :: capacity()是“ vector”头文件的库函数,用于查找矢量的容量,它返回当前分配给该矢量的存储空间。
注意:要使用向量,请包含<vector>标头。
vector :: capacity()函数的语法
vector::capacity();
参数: void –不接受任何参数。
返回值: size_type –返回容量,即向量的存储空间。
示例
Input: vector<int> vector1{ 1, 2, 3, 4, 5 }; Function call: cout << vector1.capacity(); Output: 8
//C ++ STL程序演示示例 //vector :: capacity()函数 #include <iostream> #include <vector> using namespace std; int main(){ vector<int> v1; //printing the size & capacity of the vector cout << "Total number of elements: " << v1.size() << endl; cout << "Storage space: " << v1.capacity() << endl; //推动元素 v1.push_back(10); v1.push_back(20); v1.push_back(30); v1.push_back(40); v1.push_back(50); //printing the size & capacity of the vector cout << "Total number of elements: " << v1.size() << endl; cout << "Storage space: " << v1.capacity() << endl; return 0; }
输出结果
Total number of elements: 0 Storage space: 0 Total number of elements: 5 Storage space: 8
参考:C ++ vector :: capacity()