如何在C ++中初始化向量?
初始化向量可以通过多种方式完成
1)通过push_back()方法初始化向量
算法
BeginDeclare v of vector type.
Call push_back() function to insert values into vector v.
Print “向量元素:”.
for (int a : v)
print all the elements of variable a.
End.
示例
#include<iostream>#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v;
v.push_back(6);
v.push_back(7);
v.push_back(10);
v.push_back(12);
cout<<"向量元素:"<<endl;
for (int a : v)
cout << a << " ";
return 0;
}
输出结果
向量元素:6 7 10 12
2)通过数组初始化向量
算法
BeginCreate a vector v.
Initialize vector like array.
Print the elements.
End.
示例
#include <bits/stdc++.h>using namespace std;
int main() {
vector<int> v{ 1, 2, 3, 4, 5, 6, 7 };
cout<<"向量元素:"<<endl;
for (int a : v)
cout << a << " ";
return 0;
}
输出结果
向量元素:1 2 3 4 5 6 7
3)从另一个向量初始化一个向量
算法
BeginCreate a vector v1.
Initialize vector v1 by array.
Initialize vector v2 by v1.
Print the elements.
End.
示例
#include<iostream>#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v1{ 1, 2, 3, 4, 5, 6, 7 };
vector<int> v2(v1.begin(), v1.end());
cout<<"向量元素:"<<endl;
for (int a : v2)
cout << a << " ";
return 0;
}
输出结果
向量元素:1 2 3 4 5 6 7
4)通过指定大小和元素来初始化向量
算法
BeginInitialize a variable s.
Create a vector v with size s and all values with 7.
Initialize vector v1 by array.
Initialize vector v2 by v1.
Print the elements.
End.
示例
#include<iostream>#include <bits/stdc++.h>
using namespace std;
int main() {
int s= 5;
vector<int> v(s, 7);
cout<<"向量元素:"<<endl;
for (int a : v)
cout << a << " ";
return 0;
}
输出结果
向量元素:7 7 7 7 7
以上是 如何在C ++中初始化向量? 的全部内容, 来源链接: utcz.com/z/359708.html