当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。