STL(四)vector

  • 定义
    • 顺序容器
    • 动态数组,成员存储在连续空间
    • 迭代器或指针访问成员
    • 随机访问成员或在头尾添加、删除成员效率比较高(相对list。。。)
  • 操作
    • 构造函数:
      • 1   vector<int> first;                                // empty vector of ints
        2   vector<int> second (4,100);                       // four ints with value 100
        3   vector<int> third (second.begin(),second.end());  // iterating through second
        4   vector<int> fourth (third);                       // a copy of third
        5 
        6   // the iterator constructor can also be used to construct from arrays:
        7   int myints[] = {16,2,77,29};
        8   vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
    • operator=:Copy vector content
    • empty:是否为空
    • size与capacity:size为成员个数,capacity为容器大小(capacity>=size)。通过resize和reserve修改二者。
    • 成员访问:[]、at、front、back。
      • []与at都是访问任意位置成员,但是当越界操作时at会抛出out_of_range异常,便于查找问题。
    • 修改成员:
      • push_back
      • pop_back
      • erase
      • clear:size==0
      • swap:交换两vector内容
      • assign:
         1   vector<int> first;
         2   vector<int> second;
         3   vector<int> third;
         4 
         5   first.assign (7,100);             // a repetition 7 times of value 100
         6 
         7   vector<int>::iterator it;
         8   it=first.begin()+1;
         9 
        10   second.assign (it,first.end()-1); // the 5 central values of first
        11 
        12   int myints[] = {1776,7,4};
        13   third.assign (myints,myints+3);   // assigning from array.

         

posted @ 2012-06-18 09:34  iThinking  阅读(198)  评论(0编辑  收藏  举报