zoukankan      html  css  js  c++  java
  • 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中迭代器就是元素的指针,这下终于看清楚啦,原来就是先确认有足够的空间,然后调用相应类型的赋值(=)函数。

  • 相关阅读:
    ansible设置串行的方法
    给k8s集群中的node节点加标签
    Prometheus断电后启动异常 Error on ingesting samples
    配置 containerd 镜像仓库完全攻略
    这款网络排查工具,堪称神器!
    k8s备份工具之velero
    CentOS 7安装megacli
    Atitit .h5文件上传 v3
    php切片处理视频大文件思路
    php切片处理视频大文件功能
  • 原文地址:https://www.cnblogs.com/chenhuan001/p/7191488.html
Copyright © 2011-2022 走看看