c++ vector详解

容器有太多需要清楚细节的地方,同时也有太多值得学习的地方。下文作为学习、工作中用到vector的总结。

1. 赋值运算=的实现原理

在使用赋值操作时,如果不清楚内部是怎么实现,那么用起来会畏手畏脚。

先来看下stl_vector.h中对于=的重载函数。

template <class T, class Alloc>    
vector<T, Alloc>& vector<T, Alloc>::operator=(const vector<T, Alloc>& x)    
{    
  if (&x != this) {    
    // 如果x.size() > capacity()那么就需要重新分配内存    
    // 首先分配内存, 并将容器内原来的元素拷贝到新分配内存中    
    // 然后析构原容器中元素, 调整内存状态变量    
    if (x.size() > capacity()) {    
      iterator tmp = allocate_and_copy(x.end() - x.begin(),    
                                       x.begin(), x.end());    
      destroy(start, finish);    
      deallocate();    
      start = tmp;    
      end_of_storage = start + (x.end() - x.begin());    
    }    
    else if (size() >= x.size()) {    
      iterator i = copy(x.begin(), x.end(), begin());    
      destroy(i, finish);    
    }    
    else {    
      copy(x.begin(), x.begin() + size(), start);    
      uninitialized_copy(x.begin() + size(), x.end(), finish);    
    }    
    finish = start + x.size();    
  }    
  return *this;    
}    

从上述代码发现,上述代码处理了容量问题,却没有写出copy细节,然后我们继续去找。

在stl_algobase.h中找到了copy的代码,(copy调用了__copy)

template <class _InputIter, class _OutputIter, class _Distance>
inline _OutputIter __copy(_InputIter __first, _InputIter __last,
                          _OutputIter __result,
                          input_iterator_tag, _Distance*)
{
  for ( ; __first != __last; ++__result, ++__first)
    *__result = *__first;
  return __result;
}

而stl中迭代器就是元素的指针,这下终于看清楚啦,原来就是先确认有足够的空间,然后调用相应类型的赋值(=)函数。

 

posted @ 2017-07-16 19:29  chenhuan001  阅读(319)  评论(0编辑  收藏  举报