提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
vector(矢量),变长数组
即“自动改变数组长度的数组”。
一、vector定义
vector<类型名> 变量名;
vector<int> name;
vector<double> name;
vector<char> name;
vector<struct node> name;
vector<vector<int> > name;//注意:> >之间要加空格
vector数组就是一个一维数组,如果定义成vector数组的数组,那就是二维数组。
vector<int> array[SZIE]; //二维变长数组
二、vector容器内元素的访问
1.通过下标访问
代码如下(示例):
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> vi;
vi.push_back(1);
cout<<vi[0]<<endl;
return 0;
}
类似数组。
2.通过迭代器访问
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
for (int i = 0; i < 5; i++)
{
v.push_back(i);
}
//v.begin()返回v的首元素地址
vector<int>::iterator it=v.begin();
for (int i = 0; i < v.size(); i++)
{
cout<<it[i]<<" ";
}
return 0;
}
类似链表。
it[i] = *(it+i)
这两个写法等价
for (vector<int>::iterator it=v.begin(); it!=v.end();it++)
{
cout<<*it<<" ";
}
在for循环中定义it。
三、vector常用函数
push_back()
void std::vector<int>::push_back(const int &__x)
在vector后面添加一个元素item。压入取代了赋值。
pop_back()
void std::vector<int>::pop_back()
pop_back()一次弹出一个元素,vector容器就会减少一个预算。
size()
std::size_t std::vector<int>::size()
szie()返回vector中所含元素的个数,时间复杂度为O(1)。
clear()
void std::vector<int>::clear()
clear()用于一键清空vector中的所有元素,时间复杂度为O(N),其中N为vector中原属和元素的个数。
insert()
insert(__position,__x);
插入(地址,元素);
参数:
__position:– A const_iterator into the %vector.
__x:– Data to be inserted.
erase()
erase(__position);
erase(__positionBegin,__positionEnd);
begin()
类似头指针。
end()
类似尾指针。
next_permutation()
next_permutation(nums.begin(),nums.end())
返回下一次更大的排列
三、vector常见用途
1.储存数据
vector本身可以作为数组使用,而且在一些元素个数不确定的场合可以很好地节省空间。
2.用邻接表存储图
使用vector实现邻接表,更为简单。