您的位置:首页 > 其它

第一部分 基本语言 第三章 标准库类型(3.3标准库vector类型)

2013-04-02 22:10 423 查看
3.3标准库vector类型

一、vector

vector是同一种类型对象的集合,对每个对象都有一个对应的整数索引值。标准库负责管理和存储相关内存,我们把vector成为容器,它可以包含其他对象,一个容器中的所有对象都必须是同一种类型。这里贴一段来自http://www.cplusplus.com/reference/vector/vector/的介绍。讲得更加清楚。

Vector

Vectors are sequence containers representing arrays that can change in 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.

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).

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 (deques, lists 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.

vector是一个类模版,可以用来编写不同数据类型的类定义或是函数定义。必须说明vector保存何种对象的类型,形式:vector<数据类型>类型名;

二、vector对象的定义和初始化:

vector类型模版定义了几种构造函数来初始化vector对象。

vector<T> v1保存类型为T的对象,默认构造函数,v1为空。

vector<T> v2(v1)v2是v1的一个副本。

vector<T> v3(n,i) n个值为i的元素。

vector<T> v4(n)v4是含有初始化值的n个副本。

创建非空的vector对象需要给出初始化值,当把一个vector对象复制到另一个vector对象时,新复制的vector中的每一个元素都初始化为原来vector中对应值的副本,前提是这两个vector对象保持同一种类型

如果没有指定值的初始化式,vector将根据对象类型提供相应的构造函数进行初始化,对于没有定义构造函数的情况,vector仍将提供一个初始值。

三、vector提供的操作:

vector对象提供了许多类似于前面所说的string对象的操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐