STL——vector

来源:互联网 发布:电信 网络重构 编辑:程序博客网 时间:2024/04/30 17:44

参考自CPP标准文档vector


一、定义

Vectors are sequence containers representing arrays that can change in size

特点:

1.  Sequence

    Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by their position in this sequence.

2. Dynamic array

    Allows direct access to any element in the sequence, even through pointer arithmetics(算数:加减乘除), and provides relatively fast addition/removal of elements at the end of the sequence.

3. Allocator-aware

    The container uses an allocator object to dynamically handle its storage needs


初始化

// constructors used in the same order as described above:  std::vector<int> first;                                // empty vector of ints  std::vector<int> second (4,100);                       // four ints with value 100  std::vector<int> third (second.begin(),second.end());  // iterating through second  std::vector<int> fourth (third);                       // a copy of third  // the iterator constructor can also be used to construct from arrays:  int myints[] = {16,2,77,29};  std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

 vector 的data成员,返回指向数组的首地址,因为vector是线性连续存储的,所以可以通过指针的偏移访问vector的元素。

#include <iostream>#include <vector>int main (){  std::vector<int> myvector (5);  int* p = myvector.data();  *p = 10;  ++p;  *p = 20;  p[2] = 100;  std::cout << "myvector contains:";  for (unsigned i=0; i<myvector.size(); ++i)    std::cout << ' ' << myvector[i];  std::cout << '\n';  return 0;}

Output:

myvector contains: 10 20 0 100 0


swap

vector的交换大小可以不一样,同array不同(array的size必须一样才可以交换)


使用区别:

1、如果你需要高效的随机存取(即[]操作),不在乎插入和删除的效率,应该使用vector

2.  如果你需要大量的插入和删除,不关心随机存取,应该使用list

3. 如果你需要随机存取,而且关心数据的插入删除,应该使用deque



0 0