Vector是一个线性容器,它和数组很类似,它们的元素会分配在一段连续的内存区域之中,因此它可以使用下标快速访问某一个元素,在容器末尾增删元素也很方便,而且使用vector的好处在于可以动态增长或缩小存储空间。Vector的缺点也和数组类似,就是在容器中进行增删操作就比较低效了。
对于Vector来说,它的size和capacity是有区别的,size是指你这个容器目前包含的元素,调用vector::size()返回目前元素个数,capacity指的是容器可以容纳的元素个数,调用vector::capacity()返回容量值。当不断向一个vector容器添加元素时,会出现size大于capacity的情况,这时就会自动重新分配内存以扩大vector的capacity,也可以自己指定分配的容量大小,使用vector::reserve()实现,注意设定的值要大于size()的值。每次重新分配内存都很影响程序的性能!
vector的遍历方法和增删改示例
vector的遍历方法有三种:1.下标遍历;2.迭代器遍历;3.for_each方法遍历。本人较常用1、2两种方法,方法3基本没用过。
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
void print(int n) {
cout << n << " ";
}
int main() {
int a[7] = { 1,2,3,4,5,6,7 };
//vector赋值
vector<int> ivector(a, a + 7);
//vector遍历方式一:迭代器遍历
vector<int>::iterator it;
for(it = ivector.begin();it!=ivector.end();it++){
cout << *it << " ";
}
cout << endl;
//vector遍历方式二:下标遍历
for (int i = 0; i < ivector.size(); i++) {
cout << ivector[i] << " ";
}
cout << endl;
//vector遍历方式三:for_each遍历
for_each(ivector.begin(), ivector.end(), print);
cout << endl;
return 0;
}
当Vector容器存放的是结构体时,可以在结构体中写好排序的重载函数,或者在结构体外写一个比较函数,使用<algorithm>中的sort排序。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef struct rect {
int id;
double length;
double width;
bool operator <(const rect &a)const {
if (id != a.id) {
return id < a.id;
}
else {
if (length != a.length) return length < a.length;
else return width < a.width;
}
}
rect(int id1, int length1, int width1) {
id = id1;
length = length1;
width = width1;
}
}rect;
typedef struct rect2 {
int id;
double width;
double length;
struct rect2(int id1, int length1, int width1) {
id = id1;
length = length1;
width = width1;
}
}rect2;
int cmp(rect2 a, rect2 b) {
if (a.id != b.id) return a.id < b.id;
else {
if (a.length != b.length) return a.length < b.length;
else return a.width < b.width;
}
}
int main() {
//结构体遍历方式一:重载结构体内部比较函数
vector<rect> vec;
vec.push_back(rect(2, 3, 4));
vec.push_back(rect(1, 2, 3));
vector<rect>::iterator it = vec.begin();
sort(vec.begin(), vec.end());
cout << (*it).id << ' ' << (*it).length << ' ' << (*it).width << endl;
//结构体遍历方式二:结构体外写比较函数
vector<rect2> vec2;
vec2.push_back(rect2(2, 3, 4));
vec2.push_back(rect2(1, 2, 3));
vector<rect2>::iterator it2 = vec2.begin();
sort(vec2.begin(), vec2.end(), cmp);
cout << (*it2).id << ' ' << (*it2).length << ' ' << (*it2).width << endl;
return 0;
}
Vector的查找和删除
vector的查找可以使用<algorithm>中的find函数来实现。
vector的删除,可以用pop_back删除最后一个位置,也可使用erase删除指定位置的元素。