vector的用法
来源:互联网 发布:中小型网络拓扑及搭建 编辑:程序博客网 时间:2024/06/06 00:27
介绍
vector是C++标准模板库,是一个容器,可以理解为动态数组。
命名空间为std,所属头文件为 注意:不是 < vector.h >
vector存储数据时,会分配一个存储空间,如果继续存储,该分配的空间已满,就会
分配一块更大的内存,把原来的数据复制过来,继续存储,这些性能也会一定程度上会>有损耗。
vector常用方法
1.容量
a.vector大小:vector.size()
b.vector所占内存实际大小:vector.capacity()
2.修改
a.尾部添加元素:vector.push_back()
b.尾部删除元素:vector.pop_back()
c.交换两个vector元素:vector.swap()
d.清空vector元素:vector.clear()
3.迭代器
a.vector开始指针:vector.begin()
b.vector尾部指针:vector.end()
4.访问元素
a.下标访问:vector[1] //不检查是否越界
b.at方法访问:vector.at(1) //自动检查是否越界,如越界会抛出异常
c.访问第一个元素:vector.front()
d.访问最后一个元素:vector.back()
vector存储
简单存储
[html] view plain copy//存储方式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); }
存储结构体和结构体指针
[html] view plain copystruct Student { char name[32]; int age; };
//存储结构体
vector<Student> vStu1; for (int i=0; i<10; i++) { Student stu; strcpy(stu.name, "wangpengfei"); 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, "wangpengfei"); pStu->age = 30 + i; vStu2.push_back(pStu); }
vector遍历
[html] view plain copyvector<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); }
vector释放内存
存放整形vector释放
[html] view plain copy
//存放整型
vector<int> v; for (int i=0; i<100; i++) { v.push_back(i); }
//释放内存
vector<int> (v).swap(v);
存放结构体vector释放
[html] view plain copy
//存储结构体
vector<Student> vStu1; for (int i=0; i<10; i++) { Student stu; strcpy(stu.name, "wangpengfei"); stu.age = 30 + i; vStu1.push_back(stu); }
//释放内存
vector<Student> (vStu1).swap(vStu1);
存放结构体指针vector释放
[html] view plain copy
//存储结构体指针
vector<Student*> vStu2; for (int i=0; i<10; i++) { Student* pStu = (Student*)malloc(sizeof(Student)); strcpy(pStu->name, "wangpengfei"); pStu->age = 30 + i; vStu2.push_back(pStu); }
//释放内存
for (vector<Student*>::iterator it = vStu2.begin(); it != vStu2.end(); it++) { if (NULL != *it) { delete *it; *it = NULL; } }
- Vector的用法
- Vector的用法
- Vector的用法
- Vector类的用法
- Vector的用法
- Vector的用法
- vector的用法
- vector的用法
- vector的基本用法
- java Vector的用法
- Vector的用法
- C++ Vector的用法
- STL Vector的用法
- vector的用法
- vector的用法
- vector的用法
- Vector的用法
- C++ vector的用法
- 使用plt *.log
- hdu 1078(记忆化搜索)
- (M)BFS:310. Minimum Height Trees
- 字符串hash——Codeforces533F Encoding
- 开博客,记录
- vector的用法
- autofs服务之光盘自动挂载
- 1061. Dating (20)
- MySQl + java-web 数据分页案例
- Relection2017.10.18
- 表格属性介绍
- 斗地主核心代码
- 设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
- HDU 3339 In Action