【C++】——vector容器
前言
对于vector,其实和string类是有点像的,但是里面的结构又有点不一样,所以有些操作是需要注意的
一 vector基本概念
1.我们使用vector的时候,可以把他当作一个数组来使用,只不过这个数组是可以自动扩容的
2.vector里面的数据是存在堆上面的,数组里面的数据是存在栈里面的,这个要区分
3.使用vector的时候需要包含#include头文件
二 vector的构造函数
函数原型:
default (1) | explicit vector (const allocator_type& alloc = allocator_type()); |
---|---|
fill (2) | explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type()); |
range (3) | template vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type()); |
copy (4) | vector (const vector& x); |
1.vector (const allocator_type& alloc = allocator_type());//无参构造函数
2.vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type());//将n个val拷贝给本身
3.vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());//使用迭代器把区间内的元素给本身
4.vector (const vector& x);//拷贝构造函数
1.explicit是限制隐式类型转换的。
2.对于第三个迭代器来说,设置为模板,这样就可以使用其他类型,而不单单限制于一种类型
3.对于const allocator_type& alloc = allocator_type()这个来说,他只是一个内存池,如果我们不写就用这个默认的,除非你觉得你比他的写得好,你就可以传进去😘😘
为了方便测试,我们遍历容器的时候使用范围for来遍历,原理其实就是迭代器
#define _CRT_SECURE_NO_WARNINGS 1 // constructing vectors #include #include using namespace std; int main() { // constructors use order as described above: vector first; //构造一个空的vector vector second(4, 100); //构造一个4个大小,val是100的vector vector third(second.begin(), second.end()); //用迭代器去初始化third这个容器 vector fourth(third); //用使用拷贝构造初始化fourth cout