vector容器 单端开口
2.1 与数组类似,但是动态分配内存;
2.2 支持随机存取,使用随机访问迭代器,普通指针也满足;一个vector的容量永远大于或等于其大小,其为动态增加大小,满载时将申请一个比原来内存更大的空间再将原始数据拷贝新空间并释放原空间(一旦引起该空间的重新配置指向原vector的迭代器将全部失效)
2.3 v.resize(int num,elem)重新指定容器长度,若变大则用elem(只一个参数时默认0)来填充多余的空间,若变小则将多的元素删除
2.4 v.first(),v.front()分别返回第一和最后一个元素
2.5 交换swap、size容器的大小、capacity 返回容器的容量、empty容器是否为空
2.6 reserve 预留空间,但是不初始化
4.7 at、[]对元素存取,at抛出异常,[]直接挂
2.8 插入 insert(迭代器),删除erase(迭代器),清空clear,尾插push_back,尾删pop_back
3、小练习
3.1巧用swap来收缩内存
3.2 巧用reserve预留空间
3.3 逆序遍历 迭代器 reverse_iterator
3.4 如何判断一个容器的迭代器是否支持随机访问
#include "pch.h"
#include <iostream>
#include<vector>
using namespace std;
void test01()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
cout << v.capacity() << endl;//v.capacity()容器的容量
}
}
void printvector(vector<int>&v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
cout << *it << " ";
cout << endl;
}
void test02()
{
vector<int>v1;
vector<int>v2(10, 100);
printvector(v2);
}
//巧用swap来收缩内存
void test04()
{
vector<int >v;
for (int i = 0; i < 100000; i++)
{
v.push_back(i);
}
cout << "v 的容量: " << v.capacity() << endl;
cout << "V 的大小: " << v.size() << endl;
v.resize(3);
cout << "v 的容量: " << v.capacity() << endl;
cout << "V 的大小: " << v.size() << endl;
//收缩内存
vector<int>(v).swap(v);//vector<int>(v)利用拷贝构造初始化匿名对象(按照大小拷贝),将该匿名对象与v交换,匿名对象被系统自动删除
cout << "v 的容量: " << v.capacity() << endl;
cout << "V 的大小: " << v.size() << endl;
}
//巧用reverse预留空间
void test05()
{
vector<int >v;
int num = 0;
int *p = NULL;
for (int i = 0; i < 100000; i++)
{
v.push_back(i);
if (p != &v[0])
{
p = &v[0];
num++;
}
}
cout << "num= " << num << endl;//num为总共开辟空间的次数和
}
void test5()
{
vector<int >v;
v.reserve(100000);
int num = 0;
int *p = NULL;
for (int i = 0; i < 100000; i++)
{
v.push_back(i);
if (p != &v[0])
{
p = &v[0];
num++;
}
}
cout << "num= " << num << endl;//num为总共开辟空间的次数和
}
void test06()
{
//逆序遍历
vector<int>v1;
v1.push_back(10);
v1.push_back(40);
v1.push_back(20);
v1.push_back(30);
cout << "正序遍历结果: " << endl;
printvector(v1);
cout << "逆序遍历结果: " << endl;
for (vector<int>::reverse_iterator it = v1.rbegin(); it != v1.rend(); it++)
cout << *it << " ";
cout << endl;
//vector容器的迭代器是随机访问迭代器
//如何判断一个容器的迭代器是否支持随机访问
vector<int>:: iterator itBegin = v1.begin();
itBegin++;
itBegin--;
//++ --通过至少为双向迭代器
itBegin == itBegin + 1;//通过为随机迭代器
}
int main()
{
//test01();
//test02();
//test04();
//test05();
//test5();
test06();
}