在C++中,向量是动态数组。与数组不同,它们没有固定的大小。它们可以根据需要增长或收缩。在连续位置的块中为向量分配了内存。当为向量分配的内存不足以存储新元素时,会将新的存储块分配给向量,并将所有元素从旧位置复制到新位置。元素的这种重新分配有助于向量在需要时增长。但是,这是一项昂贵的操作,并且此步骤涉及的时间复杂度是线性的。
std :: vector类提供了有用的函数保留,可帮助用户指定向量的最小大小,它表示创建向量的目的是可以存储至少指定数量的元素而不必重新分配内存。
std :: vector :: reserve
void reserve(size_type n)
Return Type: none
Arguments: n which denotes the no of elements to be stored in vector
Requests that vector is large enough to store n elements in the least.
If the current vector capacity is less than n, then reallocation will
take place. In other cases, reallocation will not happen. Function does
not modify existing elements in the vector
每个向量对象都有两个参数-大小和容量。大小表示向量中当前存储的元素数,而容量是向量中无需重新分配即可存储的最大元素数。显然容量> =大小。当向量空间不足以存储新元素时(即,当大小变得大于容量时),运行时库将请求堆中的新内存,一旦分配了内存,它将把向量中的所有元素从其旧地址复制到内存中。新分配的内存地址。调用函数保留区会修改向量的容量参数,因此向量请求足够的内存来存储指定数量的元素。
这是一个演示使用保留函数可以提高性能的程序。在此程序中,我们用大量元素填充两个向量,并计算执行此步骤所花费的时间。对于第一个向量,我们不指定容量,而对于第二个向量,我们使用reserve()指定容量。
// CPP program to demonstrate use of
// std::vector::reserve
#include
#include
#include
using std::vector;
using std::cout;
using namespace std::chrono;
int main()
{
// No of charactes
int N = (int)1e6;
vector v1, v2;
// Reserve space in v2
v2.reserve(N);
// Start filling up elements in v1
// To measure execution time in C++, refer below
// https://www.geeksforgeeks.org/measure-execution-time-function-cpp/
auto start = high_resolution_clock::now();
for (int i = 0; i < N; ++i)
v1.push_back(i);
auto stop = high_resolution_clock::now();
auto duration = duration_cast(stop - start);
cout << "Method I took " << duration.count() << " microseconds\n";
// Start filling up elements in v2
start = high_resolution_clock::now();
for (int i = 0; i < N; ++i)
v2.push_back(i);
stop = high_resolution_clock::now();
duration = duration_cast(stop - start);
cout << "Method II took " << duration.count()
<< " microseconds \n";
return 0;
}
输出:(取决于机器)
Method I took 18699 microseconds
Method II took 16276 microseconds
笔记:
与不指定向量大小的情况下尝试插入元素相比,可以保证预先预留空间将花费更少的时间。此外,它将语义实用程序添加到代码中,我们至少知道向量将有多大。