通过内置数组初始化 vector 容器

template< class InputIt >
vector( InputIt first, InputIt last, 
        const Allocator& alloc = Allocator() );

上面的构造函数的原型属于 vectorrange constructor
Constructs the container with the contents of the range [first, last)。
first, last - the range to copy the elements from。first、last 可以为:

  • 普通的指针
  • 迭代器(只能为vector的迭代器?)
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char *argv[]) {
    cout << "create array: ";
    int *arr = new int[4];
    for (int i = 0; i < 4; ++i) {
        arr[i] = i + 2; 
        cout << arr[i] << " ";
    }
    cout << endl;

    cout << "vector init with array: ";
    vector<int> vec(arr, arr + 4); // init by array pointer, copy action
    for (auto &var : vec) {
        cout << var << " ";
    }
    cout << endl;

    delete [] arr;
    arr = nullptr;

    cout << "after deleting the array, vector: " ;
    for (auto &var : vec) {
        cout << var << " ";
    }
    cout << endl;

    return 0;
}

vectorrange constructor 所执行的是对源数据的复制操作,上述代码输出结果可以证实这一点:

create array: 2 3 4 5
vector init with array: 2 3 4 5
after deleting the array, vector: 2 3 4 5

参考链接:
[1] std::vector::vector (cppreference)
[2] std::vector::vector (cplusplus)

猜你喜欢

转载自blog.csdn.net/pl20140910/article/details/81391293