关于vector的使用,特别好用的一些点: 1、一维数组vector使用时: 附上代码如下:
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n;
cin >> n;
int number;
vector<int> res(n,0);
for (int i = 0; i < n; i++) {
cout << res[i] << " ";
}
cout << endl;
cout << endl;
for (int i = 0; i < n; i++) {
cin >> number;
res[i]=number;
}
for (int i = 0; i < n; i++) {
cout << res[i] << " ";
}
cout << endl;
return 0;
}
运行结果如下:
2、二维数组vector使用时: 可以直接初始化,这样在往数组中存值时,就可以用赋值运算符等号,不需要用push_back函数。
vector<vector<int>> res(n,vector<int>(m,0));
在向二维数组进行输入时:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> number;
res[i][j]=number;
}
}
附上完整的代码:
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int number;
vector<vector<int>> res(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << res[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> number;
res[i][j]=number;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}
运行结果:
|