c++ STL之vector

1.new

vector<int> V;

2.push a element to V

V.push_back(element);

3.visit elements in V

  • by index

    cout << V[i];
  • by iterator
    iterator is analogous to pointer,the definer is:

    vector<typename>::iterator it;

    then 'it' is a variable,the type is 'vector<typename>::iterator',we can get the address of the element via *it

  • eg:

    vector<int>::iterator it = V.begin();
    for(int i=0; i<V.size(); i++){
        cout << *(it + i);
    }

    Note:V[ i ] is equal to *(V.begin() + i);

4.begin() and end()

  • begin() gain address of the V's first element,and end() gain next address of the V's last element,usually as the flag of the iterator's tail
  • eg:

    //vector's iterator can only utilize like this:
    for(vector<int>::iterator it = V.begin(); it != V.end(); it++)//V[i].begin is equal to V[0]
        cout << *it;

5.pop_back()

  • delete last element

    V.pop_back();

6.size()

  • return unsigned type

7.clear()

  • O(n)

    V.clear()// V.clear() is equal to V.erase(V.begin(),V.end())

8.insert()

  • insert(it,x), time complexity is O(n)

    V.insert(V.begin() + m,value);

9.erase()

  • delele single element

    V.erase(V.begin() + m);//m is index
  • delete all elements in a range:[m, k)

    V.erase(V.begin() + m,V.begin() + k);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章