Vector
下面是vector的基础使用方法。
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
for (int i = 0; i < vec.size(); i++){
cout << vec[i] << endl;
}
// 清空vec内数据
vec.clear();
for (int i = 0; i < vec.size(); i++){
cout << vec[i] << endl;
}
// 清除vec的内存
vector<int>().swap(vec);
return 0;
}
同样结构体也是可以的
#include <iostream>
#include <vector>
using namespace std;
struct Student{
string name;
int age;
};
int main(){
vector<Student>v;
Student stu1, stu2;
stu1.name = "玛卡巴卡";
stu1.age = 10;
stu2.name = "胖橙";
stu2.age = 20;
v.push_back(stu1);
v.push_back(stu2);
for (int i = 0; i < v.size(); i++){
cout << v[i].name << " " << v[i].age << endl;
}
return 0;
}
下面是快速初始化,构造的方式,vectorv中的第一个参数是长度大小。第二个参数是初始值。
#include <iostream>
#include <vector>
using namespace std;
int main(){
int n;
cin >> n;
vector<int>v(n, 0);
for (int i = 0; i < v.size(); i++){
cout << v[i] << endl;
}
return 0;
}
二维的解决方法:
int n = 5;
vector<vector<int> > vec2;
for (int i = 0; i < vec2.size(); i++){
vector<int> x(i + 1, 1);
vec2.push_back(x);
}
二维的初始化
int main(){
int n = 10, m = 5;
vector<vector<int> > vec(n, vector<int>(m, 0));
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
cout << vec[i][j] << " ";
}
cout << endl;
}
return 0;
}
|