【vector】vector妙用

一,什么是vector

Vectors are sequence containers representing arrays that can change in size.

这个是官方解释~就动态size的数组

二、有啥用

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.
//vector和数组一样是内存连续存储,但是它可以再加再减
Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.
Instead, vector containers may allocate some extra storage to accommodate for possible growth, and thus the container may have an actual capacity greater than the storage strictly needed to contain its elements (i.e., its size). Libraries can implement different strategies for growth to balance between memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing intervals of size so that the insertion of individual elements at the end of the vector can be provided with amortized constant time complexity (see push_back).
//加一个扩一个太蠢了,所以一般vector会自己开大点内存
Therefore, compared to arrays, vectors consume more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.
Compared to the other dynamic sequence containers (dequeslists and forward_lists), vectors are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements from its end. For operations that involve inserting or removing elements at positions other than the end, they perform worse than the others, and have less consistent iterators and references than lists and forward_lists.

//与其他动态序列容器(deques、lists和forward_lists)相比,vector非常高效地访问它的元素(就像数组一样),并且相对高效地从它的末端添加或删除元素。对于涉及在非结尾位置插入或删除元素的操作,它们的性能比其他操作差,而且与列表和forward_lists相比,它们的迭代器和引用的一致性更差。

还是看官网的靠谱好理解~

 

一些操作//最好去看下面的链接里的

a.swap(b);//a,b是同类型的vector变量,交换a,b内所有元素

a.clear();//清空vector a内元素

a,size();//当前a中元素的个数

a.capacity()//当前a(未分配新的储存空间前)所能容量的元素的总数

a.max_size();//a容器所能容纳的最大元素总数

a.resize(n);//创建n个元素,并为其分配空间

a.empty();//判断是否为空。为空则为1 

三、用来存特大二维数组~

主要分两种方式,一个是先开辟空间,一个是push

  1. 一次性开辟空间(n*m二维数组)      v.resize(n,vector<int > (m) );

  2. 只指定外层vector大小    v.resize(n);

  3. 指定内层vector大小(在指定了外层vector大小的前提下)for(int i=1;i<=n;i++)v[i].resize(m);

 

参考资料:http://www.cplusplus.com/reference/vector/vector/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值