Vectors:
Vectors are sequencecontainers representing arrays that can change in size.---C++ reference
Vector是可以改变大小的数组的顺序容器。
特性:
1. 动态分配连续的存储空间(vector元素可以使用下标,迭代器,指针偏移访问,在序列末尾提供相对快速的添加与删除)【注1:中间插入,删除会导致后面所有元素移动,开销大。插入删除频繁的使用list】
【注2:使用capacity()可以获取实际vector分配了多少内存,
使用reserve()可以设置capacity的大小,若reserve的大小小于此时已经分配的capacity则忽略,若大于则分配对应大小
使用size() 获取vector中实际元素多少
使用resize(),改变vector中实际元素的个数,①若大小小于现有元素个数,removingthose beyond and destroying them. 不改变capacity的大小②若大于vector的实际元素,且大于此时的capacity则重新分配更大的内存然后把后续元素赋初值,或者可以自定义默认值赋值。vector.resize(5)/vector.resize(10,默认值)
】
2. 若元素过多,会重新分配一个更大的连续空间然后把现有的拷贝过去(Allocator-aware)
【注1增长策略因编译器不同而不同,gcc++ 按一倍自增,MSVC 不提了= =摸不清套路】
【注2(避免有些人不知道备注下)重新分配的是堆上存储数据的空间,不是栈上vector对象的栈地址】
适用范围:
随机访问元素频繁,中间插入删除少.
[扩展]
如何删除vector的中所有指定元素
[备注]
iterator erase (iterator position);
iterator erase (iterator first, iterator last);
【注:STL中remove()只是将待删除元素之后的元素移动到vector的前端,而不是删除。若要真正移除,需要搭配使用erase()】
删除迭代器指向的元素,返回删除后下一个位置的迭代器,原先迭代器会变成野指针(Member type iterator is a random access iterator type that points toelements. MSVC Debug下默认赋值0xcccccccc)
code:
while (iter!=vec.end())
{
if (*iter == iData)
iter = vec.erase(iter); //删除迭代器指向的元素
else //else 因为删除后iter已经指向后一个位置,不需要自增
++iter;
}
【PS: Why vector called a "vector"】
“It's called a vector because Alex Stepanov, the designer of the StandardTemplate Library, was looking for a name to distinguish it from built-inarrays. He admits now that he made a mistake, because mathematics already usesthe term 'vector' for a fixed-length sequence of numbers. Now C++0X willcompound this mistake by introducing a class 'array' that will behave similarto a mathematical vector.Alex's lesson: be very careful every time you namesomething.”-----from stackoverflow see in the zhihu