使用 stdvector 扩展动态大小数组

// Example of std::vector as an expanding dynamic size array.
#include <algorithm>            // std::sort
#include <iostream>
#include <vector>               // std::vector
using namespace std;

int int_from( std::istream& in ) { int x = 0; in >> x; return x; }

int main()
{
    cout << "Sorting integers provided by you.\n";
    cout << "You can indicate EOF via F6 in Windows or Ctrl+D in Unix-land.\n";
    vector<int> a;      // ← Zero size by default.

    while( cin )
    {
        cout << "One number, please, or indicate EOF: ";
        int const x = int_from( cin );
        if( !cin.fail() ) { a.push_back( x ); }  // Expands as necessary.
    }

    sort( a.begin(), a.end() );
    int const n = a.size();
    for( int i = 0; i < n; ++i ) { cout << a[i] << ' '; }
    cout << '\n';
}

std::vector 是一个标准的库类模板,它提供了可变大小数组的概念。它负责所有内存管理,缓冲区是连续的,因此指向缓冲区的指针(例如 &v[0]v.data())可以传递给需要原始数组的 API 函数。通过例如附加项目的 push_back 成员函数,甚至可以在运行时扩展 vector

n push_back 操作序列的复杂性,包括向量扩展中涉及的复制或移动,是摊销 O( n )。 摊销:平均而言。

在内部,这通常通过向量加倍其缓冲区大小及其容量来实现,当需要更大的缓冲区时。例如,对于从大小为 1 开始的缓冲区,并且根据需要对 n = 17 个 push_back 调用重复加倍,这涉及 1 + 2 + 4 + 8 + 16 = 31 次复制操作,小于 2× n = 34。更一般地,该序​​列的总和不能超过 2× n

与动态大小原始数组示例相比,这种基于 vector 的代码不需要用户提供(并且知道)预先的项目数量。相反,对于用户指定的每个新项目值,仅根据需要扩展向量。