9.vector interface and underlying implementation

content

1. Common interfaces and examples of vector

1.1 vector common construction interface and sample usage

1.2 Use of vector iterators and sample usage

1.3 Common interfaces and sample usage for vector space growth

1.4 The addition, deletion and modification of vector

2. The underlying implementation of vector


1. Common interfaces and examples of vector

1.1 vector common construction interface and sample usage

(constructor) Constructor declaration Interface description
vector() (emphasis) Construct
vector without parameters (size_type n, const value_type& val = value_type()) Construct and initialize n val
vectors (const vector& x); (emphasis) Copy construct
vector ( InputIterator first, InputIterator last); use iterator for initialization construction

#include <iostream>
#include <vector>
int main ()
{
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
return 0;
}

1.2 Use of vector iterators and sample usage

Use of iterator Interface description
begin+end (emphasis) Get the iterator for the first data position , get the iterator for the next position
of the last data rbegin + rend Get the iterator for the last data position , before getting the first data an iterator of positions

#include <iostream>
#include <vector>
using namespace std;
void PrintVector(const vector<int>& v)
{
// const对象使用const迭代器进行遍历打印
vector<int>::const_iterator it = v.begin();
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}

1.3 Common interfaces and sample usage for vector space growth

Capacity space Interface description
size Get the number of data
capacity Get the capacity
empty Determine whether it is empty
resize (emphasis) Change the size of the vector
reserve (emphasis) Change the capacity of the vector

// vector::capacity
#include <iostream>
#include <vector>
int main ()
{
  size_t sz;
  std::vector<int> foo;
  sz = foo.capacity();
  std::cout << "making foo.capacity grow:\n";
  for (int i=0; i<100; ++i) {
    foo.push_back(i);//尾插元素
    if (sz!=foo.capacity()) {
      sz = foo.capacity();//当元素增加到超出capacity(容量)自动增容,将增容后容量赋值给sz
      std::cout << "capacity changed: " << sz << '\n';//同时,输出当前容量
    }
  }
}
//reserve改变vector的capacity,提前扩容,避免使用时才扩容,增加效率
std:vector<int>bar;
sz = bar.capacity();
bar.reserve(100);
std::vector<int> myvector;//构建一个空的myvector
for (int i=1;i<10;i++){//前10位尾插整数1——10
  myvector.push_back(i);
}
myvector.resize(5);//size变为5
myvector.resize(8,100);//size变为8,前八位初始化为100
myvector.resize(12);//size变为12

1.4 The addition, deletion and modification of vector

Vector additions, deletions, and changes Interface description
push_back (emphasis) Tail insertion
pop_back (emphasis) Tail deletion
find Search (note that this is an algorithm module implementation, not a member interface of vector) insert Insert val erase
before position Delete data at position swap swap two Vector's data space operator[] (emphasis) is accessed like an array


// push_back/pop_back
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int a[] = { 1, 2, 3, 4 };
vector<int> v(a, a+sizeof(a)/sizeof(int));//用数组构造vector
vector<int>::iterator it = v.begin();//迭代器打印数组
while (it != v.end()) {
cout << *it << " ";
++it;
}
cout << endl;
v.pop_back();
v.pop_back();//两次尾删
it = v.begin();
while (it != v.end()) {
cout << *it << " ";
++it;
}
cout << endl;
return 0;
}
// find / insert / erase
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
  int a[] = { 1, 2, 3, 4 };
  vector<int> v(a, a + sizeof(a) / sizeof(int));//用vector类模板构造出
  // 使用find查找3所在位置的iterator
  vector<int>::iterator pos = find(v.begin(), v.end(), 3);
  // 在pos位置之前插入30
  v.insert(pos, 30);
  vector<int>::iterator it = v.begin();
  while (it != v.end()) {
    cout << *it << " ";
    ++it;
  }
  cout << endl;
  pos = find(v.begin(), v.end(), 3);//find就是给首位,最后一位下一位迭代器+查找数值,进行查找
  // 删除pos位置的数据
  v.erase(pos);
  it = v.begin();
  while (it != v.end()) {
    cout << *it << " ";
    ++it;
  }
  cout << endl;
  return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
  int a[] = { 1, 2, 3, 4 };
  vector<int> v(a, a + sizeof(a) / sizeof(int));//构造v
  vector<int> swapv;
  swapv.swap(v);//交换两个类空间
  return 0;
};

2. The underlying implementation of vector

namespace zy

{

  template<class T>

  class vector

  {

  public:

    // Vector的迭代器是一个原生指针

    typedef T* iterator;

    typedef const T* const_iterator;

    iterator begin()
    {
      return _start;
    }

    iterator end()
    {
      return _finish;
    }

    const_iterator cbegin()
    {
      return _start;
    }

    const_iterator cend() const
    {
      return _finish;
    }



    // construct and destroy

    vector()
         :_start(nullptr)
         ,_finish(nullptr)
         ,_endOfStorage(nullptr)
    {}

    vector(int n, const T& value = T())
          : _start(nullptr)
          , _finish(nullptr)
          , _endOfStorage(nullptr)
        {
          reserve(n);
          while (n--)
          {
            push_back(value);
          }
        }

    template<class InputIterator>

    vector(InputIterator first, InputIterator last)
    {
      reserve(last - first);//开辟空间
      while (first != last)//按位插入
      {
         push_back(*first);
         ++first;
      }
    }

    vector(const vector<T>& v)//拷贝构造
        : _start(nullptr)
        , _finish(nullptr)
        , _endOfStorage(nullptr)
      {
        reserve(v.capacity());
        iterator it = begin();
        const_iterator vit = v.cbegin();
        while (vit != v.cend())//遍历赋值
        {
          *it++ = *vit++;
        }
      }

    vector<T>& operator= (vector<T> v)
    {
      swap(v);
      return *this;
    }

    ~vector()
    {
      delete[] _start;
      _start = _finish = _endOfStorage = nullptr;
    }

    // capacity

    size_t size() const 
    {
      return _finish - _start; 
    }

    size_t capacity() const
    {
      return _endOfStorage - _start;
    }

    void reserve(size_t n)
    {
      if (n > capacity())
      {
        size_t oldSize = size();
        T* tmp = new T[n];

        if (_start)
        {
          for (size_t i = 0; i < oldSize; ++i)
            tmp[i] = _start[i];
        }
        _start = tmp;
        _finish = _start + oldSize;
        _endOfStorage = _start + n;
      }
    }

    void resize(size_t n, const T& value = T())
    {
      // 1.如果n小于当前的size,则数据个数缩小到n
      if (n <= size())
      {
        _finish = _start + n;
        return;
      }
      // 2.空间不够则增容
      if (n > capacity())
        reserve(n);
      // 3.将size扩大到n
      iterator it = _finish;
      _finish = _start + n;
      while (it != _finish)
      {
        *it = value;
        ++it;
      }
    }


    ///access///

    T& operator[](size_t pos){ return _start[pos]; }

    const T& operator[](size_t pos)const{ return _start[pos]; }



    ///modify/

    void push_back(const T& x){ insert(end(), x); }

    void pop_back(){ erase(--end()); }

    void swap(vector<T>& v)
    {
        std::swap(_start, v._start);
        std::swap(_finish, v._finish);
        std::swap(_endOfStorage, v._endOfStorage);
    }

    iterator insert(iterator pos, const T& x)
    {
      assert(pos <= _finish);
      // 空间不够先进行增容
      if (_finish == _endOfStorage)
      {
        //size_t size = size();
        size_t newCapacity = (0 == capacity()) ? 1 : capacity() * 2;
        reserve(newCapacity);
        // 如果发生了增容,需要重置pos
        pos = _start + size();
      }
        iterator end = _finish - 1;
        while (end >= pos)
        {
          *(end + 1) = *end;
          --end;
        }
        *pos = x;
        ++_finish;
        return pos;
      }

    iterator erase(Iterator pos)
    {
      // 挪动数据进行删除
      iterator begin = pos + 1;
      while (begin != _finish) {
        *(begin - 1) = *begin;
        ++begin;
      }
      --_finish;
      return pos;
    }

  private:

    iterator _start; // 指向数据块的开始

    iterator _finish; // 指向有效数据的尾

    iterator _endOfStorage; // 指向存储容量的尾

  };

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324303938&siteId=291194637