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