STL——vector

参考自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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值