- 逐个push_back
// CPP program to create an empty vector
// and push values one by one.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Create an empty vector
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
vect.push_back(30);
for (int x : vect)
cout << x << " ";
return 0;
}
- 指定大小并初始化所有值
// CPP program to create an empty vector
// and push values one by one.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 3;
// Create a vector of size n with
// all values as 10.
vector<int> vect(n, 10);
for (int x : vect)
cout << x << " ";
return 0;
}
-
像数组一样初始化
// CPP program to initialize a vector like
// an array.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vect{ 10, 20, 30 };
for (int x : vect)
cout << x << " ";
return 0;
}
-
使用数组初始化
// CPP program to initialize a vector from
// an array.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int arr[] = { 10, 20, 30 };
int n = sizeof(arr) / sizeof(arr[0]);
vector<int> vect(arr, arr + n);
for (int x : vect)
cout << x << " ";
return 0;
}
-
使用另一个vector初始化
// CPP program to initialize a vector from
// another vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vect1{ 10, 20, 30 };
vector<int> vect2(vect1.begin(), vect1.end());
for (int x : vect2)
cout << x << " ";
return 0;
}
以上内容转载自: https://www.geeksforgeeks.org/initialize-a-vector-in-cpp-different-ways/,作者: Kartik
以下为vector和数组的互相初始化示例:
(转载自: https://www.iteye.com/blog/xiangjie88-871115, 作者:xiangjie88)
1. #include<iostream>
2. #include<vector>
3. using namespace std;
4. //数组初始化vector
5. int main()
6. {
7. int a[]={1,2,3,4,5};
8. vector<int> v(a,a+4);
9. for(vector<int>::iterator iter=v.begin();
10. iter!=v.end();
11. ++iter)
12. {
13. cout<<*iter<<endl;
14. }
15. }
16. //vector初始化数组
17. int main()
18. {
19. vector<int> v;
20. for(int i=0;i<5;i++)
21. v.push_back(i);
22. int a[5];
23. for(int i=0;i<v.size();i++)
24. a[i]=v[i];
25. for(int i=0;i<sizeof(a)/sizeof(int);i++)
26. cout<<a[i];
27. cout<<endl;
28. }