當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ vector::capacity()用法及代碼示例


C++ vector::capacity() 函數

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++程序演示vector::capacity()函數的例子

//C++ STL program to demonstrate example of
//vector::capacity() function

#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;

    //pushing elements
    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()



相關用法


注:本文由純淨天空篩選整理自 vector::capacity() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。