c++ 初始化 vector的七种方法

c++ 初始化 vector

vector_name.push_back(value);

vector vector_name(size, default_value);

vector vector_name = {v1, v2, v3 …};

vector vector_name(arr, arr + size);

vector vector_name(vec1.begin(), vec1.end());

fill(vector_name.begin(), vector_name.end(), value);

iota(vector_name.begin(), vector_name.end(), value);

#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

int main()
{
    // 1 C++ program to create an empty
    // vector and push values one
    // by one.
    vector<int> vect1;

    vect1.push_back(10);
    vect1.push_back(20);
    vect1.push_back(30);

    for (int x : vect1)
        cout << x << " ";
    cout << endl;


    // 2 Create a vector of size n with
    // all values as 10.
    int n = 3;
    vector<int> vect2(n, 10);
    for (int x : vect2)
        cout << x << " ";
    cout << endl;

    //3
    vector<int> vect3{ 10, 20, 30 };
    for (int x : vect3)
        cout << x << " ";
    cout << endl;

    //4
    int arr[] = { 10, 20, 30 };
    n = sizeof(arr) / sizeof(arr[0]);
    vector<int> vect4(arr, arr + n);
    for (int x : vect4)
        cout << x << " ";
    cout << endl;

    //5
    vector<int> vect5_1{ 10, 20, 30 };
    vector<int> vect5_2(vect5_1.begin(), vect5_1.end());
    for (int x : vect5_2)
        cout << x << " ";
    cout << endl;

    //6
    vector<int> vect6(10);
    // initializing using fill() function
    int value = 5;
    fill(vect6.begin(), vect6.end(), value);
    // printing vector
    for (int x : vect6)
        cout << x << " ";
    cout << endl;

    //7
    vector<int> vec7(5);
    // initializing using iota()
    iota(vec7.begin(), vec7.end(), 1);
    // printing the vector
    for (int i = 0; i < 5; i++) {
        cout << vec7[i] << " ";
    }
    cout << endl;

    return 0;
}

Result

10 20 30
10 10 10
10 20 30
10 20 30
10 20 30
5 5 5 5 5 5 5 5 5 5
1 2 3 4 5

Reference

7 ways to Initialize Vector in C++

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值