访问元素:
- a.下标访问:vector[1] //不检查是否越界
- b.at方法访问:vector.at(1) //自动检查是否越界,如越界会抛出异常
- c.访问第一个元素:vector.front()
-
d.访问最后一个元素:vector.back()
三:存储
简单存储
//存储方式1 vector<int> v1(10); for (int i=0; i<10; i++) { v1[i] = i; } //存储方式2 vector<int> v2; for (int i=0; i<10; i++) { v2.push_back(i); }存储结构体和结构体指针
struct Student { char name[32]; int age; }; //存储结构体 vector<Student> vStu1; for (int i=0; i<10; i++) { Student stu; strcpy(stu.name, "woniu201"); stu.age = 30 + i; vStu1.push_back(stu); } //存储结构体指针 vector<Student*> vStu2; for (int i=0; i<10; i++) { Student* pStu = (Student*)malloc(sizeof(Student)); strcpy(pStu->name, "woniu201"); pStu->age = 30 + i; vStu2.push_back(pStu); }四:vector遍历
vector<int> v; for (int i=0; i<100; i++) { v.push_back(i); } //遍历方式1 for (int i=0; i<100; i++) { int& a = v[i]; printf("%d ", a); } //遍历方式2 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) { int&a = *it; printf("%d ", a); }










