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


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


C++ vector::reserve() 函數

vector::reserve()是"vector"頭的庫函數,用於請求向量分配的改變。詳細參考示例了解。

注意:要使用矢量,請包括<vector>標題。

vector::reserve() 函數的語法

    vector::reserve(n);

參數: int n- 它接受n作為參數,其中n是輸入容量。

返回值: void- 如果請求有效,則不返回任何內容。但是如果請求的容量大於向量的最大大小(vector::max_size),則會拋出 length_error 異常。

示例:案例 1:(沒有 reserve())

vector<int> arr1; //usual dynamic allocation
size = arr1.capacity();
cout << "arr1 growing with usual dynamic allocation:\n";
for (int i = 0; i < 50; ++i) {
    arr1.push_back(i);
    if (size != arr1.capacity()) {
        size = arr1.capacity();
        cout << "capacity changed to:" << size << '\n';
    }
}

在這種情況下,我們沒有使用儲備,因此增長是根據動態分配的,增加了兩倍。比如,1, 2, 4, 8, 16, 32, 64, 128.....直到max_size。

示例:案例 2:(使用 reserve())

vector<int> arr2; //using reserve
size = arr2.capacity();
arr2.reserve(50); // use of reserve function
cout << "arr2 growing with using reverse:\n";
for (int i = 0; i < 50; ++i) {
    arr2.push_back(i);
    if (size != arr2.capacity()) {
        size = arr2.capacity();
        cout << "capacity changed to:" << size << '\n';
    }
}

在這種情況下,我們沒有使用儲備,因此增長是根據動態分配的,增加了兩倍。比如,1, 2, 4, 8, 16, 32, 64, 128.....直到max_size。

C++程序演示vector::reserve()函數的例子

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int>::size_type size;

    vector<int> arr1; //usual dynamic allocation
    size = arr1.capacity();
    cout << "arr1 growing with usual dynamic allocation:\n";
    for (int i = 0; i < 50; ++i) {
        arr1.push_back(i);
        if (size != arr1.capacity()) {
            size = arr1.capacity();
            cout << "capacity changed to:" << size << '\n';
        }
    }

    vector<int> arr2; //using reserve
    size = arr2.capacity();
    arr2.reserve(50); // use of reserve function
    cout << "arr2 growing with using reverse:\n";
    for (int i = 0; i < 50; ++i) {
        arr2.push_back(i);
        if (size != arr2.capacity()) {
            size = arr2.capacity();
            cout << "capacity changed to:" << size << '\n';
        }
    }

    return 0;
}

輸出

arr1 growing with usual dynamic allocation:
capacity changed to:1
capacity changed to:2
capacity changed to:4
capacity changed to:8
capacity changed to:16
capacity changed to:32
capacity changed to:64
arr2 growing with using reverse:
capacity changed to:50

參考:C++ vector::reserve()



相關用法


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