关于vector解析

Vector源码超详细解析【不看会后悔系列】 在对Vector(向量)做解析前,首先对Vector与ArrayList进行下对比: 相同点: 1.底层都是基于动态Object数组实现的 2.相同的继承与实现 3.初试默认长度都是10 区别: 1.Vector的实现是同步的/线程安全,ArrayList不同步/线程不安全。 2.扩容机制——扩容大小不同,Vector增长为原来的1倍,ArrayList增长为原来的0.5倍。 3.Vector有三... 阅读详情

本文主要参考《STL源码剖析》

我们经常使用vector,但是它究竟是什么呢?它是如何实现的?以及它的优缺点又如何?

在介绍vector之前,首先我们来了解什么是序列式容器

序列式容器:就是其中的元素都可序,但未必有序。C++中提供了array,STL中的有vector,list,deque,stack,queue等等。


vector 向量 相当于一个数组
  在内存中分配一块连续的内存空间进行存储。支持不指定vector大小的存储。STL内部实现时,首先分配一个非常大的内存空间预备进行存储,即capacituy()函数返回的大小,当超过此分配的空间时再整体重新放分配一块内存存储,这给人以vector可以不指定vector即一个连续内存的大小的感觉。通常此默认的内存分配能完成大部分情况下的存储。
  优点:(1) 不指定一块内存大小的数组的连续存储,即可以像数组一样操作,但可以对此数组
               进行动态操作。通常体现在push_back() pop_back()
               (2) 随机访问方便,即支持[ ]操作符和vector.at()
               (3) 节省空间。
   缺点:(1) 在内部进行插入删除操作效率低。
               (2) 只能在vector的最后进行push和pop,不能在vector的头进行push和pop。
               (3) 当动态添加的数据超过vector默认分配的大小时要进行整体的重新分配、拷贝与释
                     放 

最后,给大家看看vector在STL中的源码:

stl_vector.h
 *
 * Copyright (c) 1994
 * Hewlett-Packard Company
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Hewlett-Packard Company makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 *
 * Copyright (c) 1996
 * Silicon Graphics Computer Systems, Inc.
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Silicon Graphics makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 */


/* NOTE: This is an internal header file, included by other STL headers.
 *   You should not attempt to use it directly.
 */


#ifndef __SGI_STL_INTERNAL_VECTOR_H
#define __SGI_STL_INTERNAL_VECTOR_H


__STL_BEGIN_NAMESPACE


#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma set woff 1174
#endif




////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////




// 默认allocator为alloc, 其具体使用版本请参照<stl_alloc.h>
template <class T, class Alloc = alloc>
class vector
{
public:
  // 标记为'STL标准强制要求'的typedefs用于提供iterator_traits<I>支持
  typedef T value_type;                         // STL标准强制要求
  typedef value_type* pointer;                  // STL标准强制要求
  typedef const value_type* const_pointer;
  // 由于vector的特性, 一般我们实作的时候都分配给其连续的内存空间,
  // 所以其迭代器只需要定义成原生指针即可满足需要
  typedef value_type* iterator;                 // STL标准强制要求
  typedef const value_type* const_iterator;
  typedef value_type& reference;                // STL标准强制要求
  typedef const value_type& const_reference;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;            // STL标准强制要求


#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
  typedef reverse_iterator<const_iterator> const_reverse_iterator;
  typedef reverse_iterator<iterator> reverse_iterator;
#else /* __STL_CLASS_PARTIAL_SPECIALIZATION */
  typedef reverse_iterator<const_iterator, value_type, const_reference,
                           difference_type>  const_reverse_iterator;
  typedef reverse_iterator<iterator, value_type, reference, difference_type>
          reverse_iterator;
#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */


protected:
  // 这个提供STL标准的allocator接口
  typedef simple_alloc<value_type, Alloc> data_allocator;


  iterator start;               // 内存空间起始点
  iterator finish;              // 当前使用的内存空间结束点
  iterator end_of_storage;      // 实际分配内存空间的结束点


  void insert_aux(iterator position, const T& x);


  // 释放分配的内存空间
  void deallocate()
  {
    // 由于使用的是data_allocator进行内存空间的分配,
    // 所以需要同样嗲用data_allocator::deallocate()进行释放
    // 如果直接释放, 对于data_allocator内部使用内存池的版本
    // 就会发生错误
    if (start) data_allocator::deallocate(start, end_of_storage - start);
  }


  void fill_initialize(size_type n, const T& value)
  {
    start = allocate_and_fill(n, value);
    finish = start + n;                         // 设置当前使用内存空间的结束点
    // 构造阶段, 此实作不多分配内存,
    // 所以要设置内存空间结束点和, 已经使用的内存空间结束点相同
    end_of_storage = finish;
  }


public:
  // 获取几种迭代器
  iterator begin() { return start; }
  const_iterator begin() const { return start; }
  iterator end() { return finish; }
  const_iterator end() const { return finish; }
  reverse_iterator rbegin() { return reverse_iterator(end()); }
  const_reverse_iterator rbegin() const {
    return const_reverse_iterator(end());
  }
  reverse_iterator rend() { return reverse_iterator(begin()); }
  const_reverse_iterator rend() const {
    return const_reverse_iterator(begin());
  }


  // 返回当前对象个数
  size_type size() const { return size_type(end() - begin()); }
  size_type max_size() const { return size_type(-1) / sizeof(T); }
  // 返回重新分配内存前最多能存储的对象个数
  size_type capacity() const { return size_type(end_of_storage - begin()); }
  bool empty() const { return begin() == end(); }
  reference operator[](size_type n) { return *(begin() + n); }
  const_reference operator[](size_type n) const { return *(begin() + n); }


  // 本实作中默认构造出的vector不分配内存空间
  vector() : start(0), finish(0), end_of_storage(0) {}


////////////////////////////////////////////////////////////////////////////////
// 本实作中给定个数和对象, 则只分配所需内存, 不会多分配
////////////////////////////////////////////////////////////////////////////////
//                    vector(size_type n, const T& value)
//                                   ↓
//                         fill_initialize(n, value)
//                                   ↓
//                        allocate_and_fill(n, value)
//                                   ↓
//          data_allocator::allocate(n)          <stl_alloc.h>
//          uninitialized_fill_n(result, n, x)  <stl_uninitialized.h>
////////////////////////////////////////////////////////////////////////////////


  vector(size_type n, const T& value) { fill_initialize(n, value); }
  vector(int n, const T& value) { fill_initialize(n, value); }
  vector(long n, const T& value) { fill_initialize(n, value); }


  // 需要对象提供默认构造函数
  explicit vector(size_type n) { fill_initialize(n, T()); }


////////////////////////////////////////////////////////////////////////////////
// 复制构造, 同样不会多分配内存
////////////////////////////////////////////////////////////////////////////////
//                     vector(const vector<T, Alloc>& x)
//                                   ↓
//         allocate_and_copy(x.end() - x.begin(), x.begin(), x.end());
//                                   ↓
//        data_allocator::allocate(n)              <stl_alloc.h>
//        uninitialized_copy(first, last, result); <stl_uninitialized.h>
////////////////////////////////////////////////////////////////////////////////


  vector(const vector<T, Alloc>& x)
  {
    start = allocate_and_copy(x.end() - x.begin(), x.begin(), x.end());
    finish = start + (x.end() - x.begin());
    end_of_storage = finish;
  }


// 复制指定区间的元素, 同样不多分配内存
#ifdef __STL_MEMBER_TEMPLATES
////////////////////////////////////////////////////////////////////////////////
// 复制一个区间进行构造, 可能会导致多分配内存
////////////////////////////////////////////////////////////////////////////////
//               vector(InputIterator first, InputIterator last)
//                                   ↓
//            range_initialize(first, last, iterator_category(first));
//                                   ↓
//                     for ( ; first != last; ++first)
//                         push_back(*first);
//            由于使用push_back()操作, 可能导致多次重复分配内存,个人感觉应该先
//            data_allocator::allocate((last - first) * sizeof(T));
//            然后uninitialized_copy(first, last, result);
//            这样不会多分配内存, 也不会导致多次重新分配内存问题
////////////////////////////////////////////////////////////////////////////////


  template <class InputIterator>
  vector(InputIterator first, InputIterator last) :
    start(0), finish(0), end_of_storage(0)
  {
    range_initialize(first, last, iterator_category(first));
  }
#else /* __STL_MEMBER_TEMPLATES */


////////////////////////////////////////////////////////////////////////////////
// 复制一个区间进行构造, 可能会导致多分配内存
////////////////////////////////////////////////////////////////////////////////
//              vector(const_iterator first, const_iterator last)
//                                   ↓
//                        distance(first, last, n);
//                                   ↓
//                      allocate_and_copy(n, first, last);
//                                   ↓
//       data_allocator::allocate(n)               <stl_alloc.h>
//       uninitialized_copy(first, last, result);  <stl_uninitialized.h>
////////////////////////////////////////////////////////////////////////////////


  vector(const_iterator first, const_iterator last) {
    size_type n = 0;
    distance(first, last, n);
    start = allocate_and_copy(n, first, last);
    finish = start + n;
    end_of_storage = finish;
  }
#endif /* __STL_MEMBER_TEMPLATES */


  ~vector()
  {
    // 析构对象
    destroy(start, finish);
    // 释放内存
    deallocate();
  }


  vector<T, Alloc>& operator=(const vector<T, Alloc>& x);


////////////////////////////////////////////////////////////////////////////////
// 预留一定空间, 如果n < capacity(), 并不会减少空间
////////////////////////////////////////////////////////////////////////////////
//                          reserve(size_type n)
//                                   ↓
//                   allocate_and_copy(n, start, finish)
//                   destroy(start, finish);               <stl_construct.h>
//                   deallocate();
////////////////////////////////////////////////////////////////////////////////


  void reserve(size_type n)
  {
    if (capacity() < n) {
      const size_type old_size = size();
      iterator tmp = allocate_and_copy(n, start, finish);
      destroy(start, finish);
      deallocate();
      start = tmp;
      finish = tmp + old_size;
      end_of_storage = start + n;
    }
  }


  // 提供访问函数
  reference front() { return *begin(); }
  const_reference front() const { return *begin(); }
  reference back() { return *(end() - 1); }
  const_reference back() const { return *(end() - 1); }


////////////////////////////////////////////////////////////////////////////////
// 向容器尾追加一个元素, 可能导致内存重新分配
////////////////////////////////////////////////////////////////////////////////
//                          push_back(const T& x)
//                                   |
//                                   |---------------- 容量已满?
//                                   |
//               ----------------------------
//           No  |                          |  Yes
//               |                          |
//               ↓                          ↓
//      construct(finish, x);       insert_aux(end(), x);
//      ++finish;                           |
//                                          |------ 内存不足, 重新分配
//                                          |       大小为原来的2倍
//      new_finish = data_allocator::allocate(len);       <stl_alloc.h>
//      uninitialized_copy(start, position, new_start);   <stl_uninitialized.h>
//      construct(new_finish, x);                         <stl_construct.h>
//      ++new_finish;
//      uninitialized_copy(position, finish, new_finish); <stl_uninitialized.h>
////////////////////////////////////////////////////////////////////////////////


  void push_back(const T& x)
  {
    // 内存满足条件则直接追加元素, 否则需要重新分配内存空间
    if (finish != end_of_storage) {
      construct(finish, x);
      ++finish;
    }
    else
      insert_aux(end(), x);
  }


  // 交换两个vector, 实际上是交换内部的状态指针
  void swap(vector<T, Alloc>& x)
  {
    __STD::swap(start, x.start);
    __STD::swap(finish, x.finish);
    __STD::swap(end_of_storage, x.end_of_storage);
  }


////////////////////////////////////////////////////////////////////////////////
// 在指定位置插入元素
////////////////////////////////////////////////////////////////////////////////
//                   insert(iterator position, const T& x)
//                                   |
//                                   |------------ 容量是否足够 && 是否是end()?
//                                   |
//               -------------------------------------------
//            No |                                         | Yes
//               |                                         |
//               ↓                                         ↓
//    insert_aux(position, x);                  construct(finish, x);
//               |                              ++finish;
//               |-------- 容量是否够用?
//               |
//        --------------------------------------------------
//    Yes |                                                | No
//        |                                                |
//        ↓                                                |
// construct(finish, *(finish - 1));                       |
// ++finish;                                               |
// T x_copy = x;                                           |
// copy_backward(position, finish - 2, finish - 1);        |
// *position = x_copy;                                     |
//                                                         ↓
// data_allocator::allocate(len);                       <stl_alloc.h>
// uninitialized_copy(start, position, new_start);      <stl_uninitialized.h>
// construct(new_finish, x);                            <stl_construct.h>
// ++new_finish;
// uninitialized_copy(position, finish, new_finish);    <stl_uninitialized.h>
// destroy(begin(), end());                             <stl_construct.h>
// deallocate();
////////////////////////////////////////////////////////////////////////////////


  iterator insert(iterator position, const T& x)
  {
    size_type n = position - begin();
    if (finish != end_of_storage && position == end()) {
      construct(finish, x);
      ++finish;
    }
    else
      insert_aux(position, x);
    return begin() + n;
  }


  iterator insert(iterator position) { return insert(position, T()); }


#ifdef __STL_MEMBER_TEMPLATES
////////////////////////////////////////////////////////////////////////////////
// 在指定位置插入一个区间
////////////////////////////////////////////////////////////////////////////////
//     insert(iterator position, InputIterator first, InputIterator last)
//                                   ↓
//       range_insert(position, first, last, iterator_category(first));
//                                   ↓
//                      for ( ; first != last; ++first) {
//                              pos = insert(pos, *first);
//                               ++pos;
//                      }
////////////////////////////////////////////////////////////////////////////////


  template <class InputIterator>
  void insert(iterator position, InputIterator first, InputIterator last)
  {
    range_insert(position, first, last, iterator_category(first));
  }
#else /* __STL_MEMBER_TEMPLATES */
  void insert(iterator position,
              const_iterator first, const_iterator last);
#endif /* __STL_MEMBER_TEMPLATES */


  void insert (iterator pos, size_type n, const T& x);


  void insert (iterator pos, int n, const T& x)
  {
    insert(pos, (size_type) n, x);
  }


  void insert (iterator pos, long n, const T& x)
  {
    insert(pos, (size_type) n, x);
  }


  void pop_back()
  {
    --finish;
    destroy(finish);
  }


  iterator erase(iterator position)
  {
    if (position + 1 != end())
      copy(position + 1, finish, position);
    --finish;
    destroy(finish);
    return position;
  }


////////////////////////////////////////////////////////////////////////////////
// 擦除指定区间的元素
////////////////////////////////////////////////////////////////////////////////
//                 erase(iterator first, iterator last)
//                                   ↓
//           ---------- copy(last, finish, first);      <stl_algobase.h>
//           |          destroy(i, finish);             <stl_construct.h>
//           |
//           |                                  -------------- copy(...)
//           |          特化                    |  char *特化   memmove()
//      ---------------------------------------|
//      |  泛化                                 |  wchar_t特化  copy(...)
//      |                                       -------------- memmove()
//      |
// 调用__copy_dispatch<InputIterator,OutputIterator>()(first, last, result);
// 进行__copy(first, last, result, iterator_category(first));派发
//      |
//      |
//      |                       random_access_iterator_tag
// --------------------------------------------------------------
// |  input_iterator_tag                                        |
// |                                                            |
// ↓                                                            |
// __copy(..., input_iterator_tag)                              |
// for ( ; first != last; ++result, ++first)                    |
//    *result = *first;                                         ↓
//                         __copy(..., random_access_iterator_tag)
//                         __copy_d(first, last, result, distance_type(first));
//                                              |
//                                              |
//                                              ↓
//              for (Distance n = last - first; n > 0; --n, ++result, ++first)
//                      *result = *first;
////////////////////////////////////////////////////////////////////////////////
  iterator erase(iterator first, iterator last)
  {
    iterator i = copy(last, finish, first);
    // 析构掉需要析构的元素
    destroy(i, finish);
    finish = finish - (last - first);
    return first;
  }


  // 调整size, 但是并不会重新分配内存空间
  void resize(size_type new_size, const T& x)
  {
    if (new_size < size())
      erase(begin() + new_size, end());
    else
      insert(end(), new_size - size(), x);
  }
  void resize(size_type new_size) { resize(new_size, T()); }


  void clear() { erase(begin(), end()); }


protected:
  // 分配空间, 并且复制对象到分配的空间处
  iterator allocate_and_fill(size_type n, const T& x)
  {
    iterator result = data_allocator::allocate(n);
    __STL_TRY {
      uninitialized_fill_n(result, n, x);
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }


// 分配空间并且拷贝一个区间的元素到新分配空间处
#ifdef __STL_MEMBER_TEMPLATES
  template <class ForwardIterator>
  iterator allocate_and_copy(size_type n,
                             ForwardIterator first, ForwardIterator last)
  {
    iterator result = data_allocator::allocate(n);
    __STL_TRY {
      uninitialized_copy(first, last, result);
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }
#else /* __STL_MEMBER_TEMPLATES */
  iterator allocate_and_copy(size_type n,
                             const_iterator first, const_iterator last)
  {
    iterator result = data_allocator::allocate(n);
    __STL_TRY {
      uninitialized_copy(first, last, result);
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }
#endif /* __STL_MEMBER_TEMPLATES */




#ifdef __STL_MEMBER_TEMPLATES
  // 初始化一个区间, 使用push_back()操作, 可能引发内存多次重新分配
  // 解决方案见
  // template <class InputIterator>
  // vector(InputIterator first, InputIterator last)
  // 我评注部分
  template <class InputIterator>
  void range_initialize(InputIterator first, InputIterator last,
                        input_iterator_tag)
  {
    for ( ; first != last; ++first)
      push_back(*first);
  }


  // This function is only called by the constructor.  We have to worry
  //  about resource leaks, but not about maintaining invariants.
  template <class ForwardIterator>
  void range_initialize(ForwardIterator first, ForwardIterator last,
                        forward_iterator_tag)
  {
    size_type n = 0;
    distance(first, last, n);
    start = allocate_and_copy(n, first, last);
    finish = start + n;
    end_of_storage = finish;
  }


  template <class InputIterator>
  void range_insert(iterator pos,
                    InputIterator first, InputIterator last,
                    input_iterator_tag);


  template <class ForwardIterator>
  void range_insert(iterator pos,
                    ForwardIterator first, ForwardIterator last,
                    forward_iterator_tag);


#endif /* __STL_MEMBER_TEMPLATES */
};


////////////////////////////////////////////////////////////////////////////////
// vector实现部分
////////////////////////////////////////////////////////////////////////////////


template <class T, class Alloc>
inline bool operator==(const vector<T, Alloc>& x, const vector<T, Alloc>& y)
{
  return x.size() == y.size() && equal(x.begin(), x.end(), y.begin());
}


// 字典序比较
template <class T, class Alloc>
inline bool operator<(const vector<T, Alloc>& x, const vector<T, Alloc>& y)
{
  return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
}


#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER


template <class T, class Alloc>
inline void swap(vector<T, Alloc>& x, vector<T, Alloc>& y)
{
  x.swap(y);
}


#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */


////////////////////////////////////////////////////////////////////////////////
// 重载赋值运算符
////////////////////////////////////////////////////////////////////////////////
//                  operator=(const vector<T, Alloc>& x)
//                                   |
//                                   |---------------- 是否是自赋值?
//                                   ↓
//              -----------------------------------------
//        No    |                                       | Yes
//              |                                       |
//              ↓                                       |------- 容量判断
//        return *this;                                 |
//                                                      ↓
//      -----------------------------------------------------------------
//      |x.size() > capacity()          | size() >= x.size()            | other
//      |                               |                               |
//      ↓                               ↓                               |
//  容量不足, 需要重新分配        容量足够, 只需要析构掉多余的对象             |
//  allocate_and_copy(         copy(x.begin(), x.end(), begin());       |
//      x.end() - x.begin(),   destroy(i, finish);                      |
//      x.begin(), x.end());                                            |
//  destroy(start, finish);                                             |
//  deallocate();                                                       ↓
//                     copy(x.begin(), x.begin() + size(), start);
//                     uninitialized_copy(x.begin() + size(), x.end(), finish);
////////////////////////////////////////////////////////////////////////////////


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;
}


////////////////////////////////////////////////////////////////////////////////
// 提供插入操作
////////////////////////////////////////////////////////////////////////////////
//                 insert_aux(iterator position, const T& x)
//                                   |
//                                   |---------------- 容量是否足够?
//                                   ↓
//              -----------------------------------------
//        Yes   |                                       | No
//              |                                       |
//              ↓                                       |
// 从opsition开始, 整体向后移动一个位置                     |
// construct(finish, *(finish - 1));                    |
// ++finish;                                            |
// T x_copy = x;                                        |
// copy_backward(position, finish - 2, finish - 1);     |
// *position = x_copy;                                  |
//                                                      ↓
//                            data_allocator::allocate(len);
//                            uninitialized_copy(start, position, new_start);
//                            construct(new_finish, x);
//                            ++new_finish;
//                            uninitialized_copy(position, finish, new_finish);
//                            destroy(begin(), end());
//                            deallocate();
////////////////////////////////////////////////////////////////////////////////


template <class T, class Alloc>
void vector<T, Alloc>::insert_aux(iterator position, const T& x)
{
  if (finish != end_of_storage) {       // 还有剩余内存
    construct(finish, *(finish - 1));
    ++finish;
    T x_copy = x;
    copy_backward(position, finish - 2, finish - 1);
    *position = x_copy;
  }
  else {        // 内存不足, 需要重新分配
    // 本实作中是按原内存2倍进行重新分配
    const size_type old_size = size();
    const size_type len = old_size != 0 ? 2 * old_size : 1;
    iterator new_start = data_allocator::allocate(len);
    iterator new_finish = new_start;
    // 将内存重新配置
    __STL_TRY {
      new_finish = uninitialized_copy(start, position, new_start);
      construct(new_finish, x);
      ++new_finish;
      new_finish = uninitialized_copy(position, finish, new_finish);
    }
// 分配失败则抛出异常
#       ifdef  __STL_USE_EXCEPTIONS
    catch(...) {
      destroy(new_start, new_finish);
      data_allocator::deallocate(new_start, len);
      throw;
    }
#       endif /* __STL_USE_EXCEPTIONS */
    // 析构原容器中的对象
    destroy(begin(), end());
    // 释放原容器分配的内存
    deallocate();
    // 调整内存指针状态
    start = new_start;
    finish = new_finish;
    end_of_storage = new_start + len;
  }
}


////////////////////////////////////////////////////////////////////////////////
// 在指定位置插入n个元素
////////////////////////////////////////////////////////////////////////////////
//             insert(iterator position, size_type n, const T& x)
//                                   |
//                                   |---------------- 插入元素个数是否为0?
//                                   ↓
//              -----------------------------------------
//        No    |                                       | Yes
//              |                                       |
//              |                                       ↓
//              |                                    return;
//              |----------- 内存是否足够?
//              |
//      -------------------------------------------------
//  Yes |                                               | No
//      |                                               |
//      |------ (finish - position) > n?                |
//      |       分别调整指针                              |
//      ↓                                               |
//    ----------------------------                      |
// No |                          | Yes                  |
//    |                          |                      |
//    ↓                          ↓                      |
// 插入操作, 调整指针           插入操作, 调整指针           |
//                                                      ↓
//            data_allocator::allocate(len);
//            new_finish = uninitialized_copy(start, position, new_start);
//            new_finish = uninitialized_fill_n(new_finish, n, x);
//            new_finish = uninitialized_copy(position, finish, new_finish);
//            destroy(start, finish);
//            deallocate();
////////////////////////////////////////////////////////////////////////////////


template <class T, class Alloc>
void vector<T, Alloc>::insert(iterator position, size_type n, const T& x)
{
  // 如果n为0则不进行任何操作
  if (n != 0) {
    if (size_type(end_of_storage - finish) >= n) {      // 剩下的内存够分配
      T x_copy = x;
      const size_type elems_after = finish - position;
      iterator old_finish = finish;
      if (elems_after > n) {
        uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        fill(position, position + n, x_copy);
      }
      else {
        uninitialized_fill_n(finish, n - elems_after, x_copy);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        fill(position, old_finish, x_copy);
      }
    }
    else {      // 剩下的内存不够分配, 需要重新分配
      const size_type old_size = size();
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
        new_finish = uninitialized_copy(start, position, new_start);
        new_finish = uninitialized_fill_n(new_finish, n, x);
        new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef  __STL_USE_EXCEPTIONS
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      destroy(start, finish);
      deallocate();
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}


#ifdef __STL_MEMBER_TEMPLATES


// 在指定位置插入指定区间的对象
template <class T, class Alloc> template <class InputIterator>
void vector<T, Alloc>::range_insert(iterator pos,
                                    InputIterator first, InputIterator last,
                                    input_iterator_tag)
{
  for ( ; first != last; ++first) {
    pos = insert(pos, *first);
    ++pos;
  }
}


template <class T, class Alloc> template <class ForwardIterator>
void vector<T, Alloc>::range_insert(iterator position,
                                    ForwardIterator first,
                                    ForwardIterator last,
                                    forward_iterator_tag)
{
  if (first != last) {
    size_type n = 0;
    distance(first, last, n);
    if (size_type(end_of_storage - finish) >= n) {
      const size_type elems_after = finish - position;
      iterator old_finish = finish;
      if (elems_after > n) {
        uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        copy(first, last, position);
      }
      else {
        ForwardIterator mid = first;
        advance(mid, elems_after);
        uninitialized_copy(mid, last, finish);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        copy(first, mid, position);
      }
    }
    else {
      const size_type old_size = size();
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
        new_finish = uninitialized_copy(start, position, new_start);
        new_finish = uninitialized_copy(first, last, new_finish);
        new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef __STL_USE_EXCEPTIONS
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      destroy(start, finish);
      deallocate();
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}


#else /* __STL_MEMBER_TEMPLATES */


template <class T, class Alloc>
void vector<T, Alloc>::insert(iterator position,
                              const_iterator first,
                              const_iterator last) {
  if (first != last) {
    size_type n = 0;
    distance(first, last, n);
    if (size_type(end_of_storage - finish) >= n) {
      const size_type elems_after = finish - position;
      iterator old_finish = finish;
      if (elems_after > n) {
        uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        copy(first, last, position);
      }
      else {
        uninitialized_copy(first + elems_after, last, finish);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        copy(first, first + elems_after, position);
      }
    }
    else {
      const size_type old_size = size();
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
        new_finish = uninitialized_copy(start, position, new_start);
        new_finish = uninitialized_copy(first, last, new_finish);
        new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef __STL_USE_EXCEPTIONS
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      destroy(start, finish);
      deallocate();
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}


#endif /* __STL_MEMBER_TEMPLATES */


#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma reset woff 1174
#endif


__STL_END_NAMES

#endif /* __SGI_STL_INTERNAL_VECTOR_H */


// Local Variables:
// mode:C++
// End
本博文只给出了其的解析,并未给出详细的用法和使用方法。读者可以登录http://www.cplusplus.com/reference/vector/vector/
若是想自己试着实现它,可以尝试下。


Vector集合类解析 在Java开发中,集合类是非常常用的数据结构。在这些集合类中,Vector是一个非常有用的类,可以在需要动态添加或者删除元素的时候快速操作数据。本文将会对Java中的Vector集合类进行深入解析。首先,我们将会介绍Vector的概述和源代码解析。然后,我们将会通过一个应用场景案例来展示Vector的使用方法。接着,我们会对Vector的优缺点进行分析。最后,我们将会介绍类代码方法和测试用例,并对全文进行小结和总结。Vector是Java的一个集合类,它是线程安全的。 阅读详情

相关推荐

POSS-NH2:氨基化笼型聚半倍硅氧烷的合成与应用探索

本文详细介绍了氨基化笼型聚半倍硅氧烷(POSS-NH2)的合成方法与应用。通过水解缩合与官能团转化两种主流路线,可制备出这种关键的纳米增强材料。其核心价值在于通过表面的氨基与树脂基体形成化学键合,从而显著提升复合材料的热稳定性和机械性能。文章以环氧树脂改性为例,展示了POSS-NH2在航空航天、电子封装等高性能领域的应用潜力。

grpc6streamer的博客 504

C++ Vector全面解析:从实现原理到性能优化

优势:连续内存、随机访问快、接口丰富局限:中间插入删除慢、扩容可能浪费内存适用:元素数量动态变化但访问频繁的场景。

zqmgx13291的博客 1380

【嵌入式原理系列-第七篇】ld脚本实战:从零构建MCU内存布局

本文是一篇针对嵌入式开发者的实战指南,详细讲解了如何从零开始为MCU编写ld链接器脚本以构建自定义内存布局。文章以STM32F103C8T6为例,深入剖析了MEMORY和SECTIONS指令的用法,并提供了OTA分区、非易失数据存储等高级定制案例,帮助开发者解决实际工程中的Flash与RAM管理难题,实现对程序运行的深度掌控。

weixin_29271263的博客 257

模板编程:采用vector作为底层实现stack的功能(包括初始化列表和迭代器的实现)

自定义模板采用vector实现。stack底层源码采用的是。

qq_38409301的博客 227

手把手教你用海康威视相机+DLP4500搭建双目结构光系统(附避坑指南)

本文详细介绍了如何使用海康威视相机和DLP4500搭建双目结构光三维测量系统,涵盖硬件选型、系统搭建、双目标定及三维重建等关键步骤。特别针对预算有限的开发者和实验室团队,提供实用的避坑指南和优化技巧,帮助实现0.02mm的高精度测量。

weixin_42526087的博客 469

AURIX™ TC49x芯片手册中文分享(二)

主要内容为第一章、功能模块的特征

xibaofenqi的博客 1569

C++ vector 容器浅析

C++ vector 容器浅析 文章目录C++ vector 容器浅析一、什么是vector?二、二、容器特性三、三、基本函数实现实例2.clear()清除容器中所有数据3.排序 一、什么是vector? 向量(Vector)是一个封装了动态大小数组的顺序容器(Sequence Container)。跟任意其它类型容器一样,它能够存放各种类型的对象。可以简单的认为,向量是一个能够存放任意类型的动态数组。 二、二、容器特性 1.顺序序列 顺序容器中的元素按照严格的线性顺序排序。可以通过元素在序列中的位置访问

qq_45131570的博客 1311

国产NAS哪家强?极空间&绿联&威联通&群晖对比

随着个人数据量暴增,传统网盘空间不足和下载速度慢问题愈发凸显。新势力NAS,作为数据管理领域的璀璨新星,正以其独特的互联网设计理念,引领家庭及小型办公用户向数据存储的新纪元。它不仅仅是一款产品,更是为初学者用户量身定制的贴心伙伴。其系统界面之简洁、操作流程之直观,让人一目了然,真正实现了“即插即用”的极致便捷。同时,新势力NAS在保持专业水准的同时,更提供了多样化的扩展性配置,轻松应对各种数据存储与管理需求,让家庭及小型办公场景下的数据管理变得前所未有的简单与高效。

专注大数据、云计算、人工智能、机器人领域技术传播 3675

C++ vector 深度解析:属性、方法、底层实现与扩容机制

/ 自定义比较函数});连续内存:缓存友好,访问高效动态扩容:自动管理内存尾部操作高效:适合作为栈使用中间操作低效:插入/删除需要移动元素resize():用于调整向量的大小,可以扩展或缩小向量,新增元素可以选择性地初始化。reverse():用于反转向量中元素的顺序,可以反转整个向量或向量的一部分。

m0_73740524的博客 1507

如何实现Docker镜像导入导出 ?

摘要: Docker镜像迁移与备份可通过两种方式实现:1)镜像操作(save/load)完整保存分层结构和元数据,适用于完整备份;2)容器操作(export/import)仅保存文件系统快照,适合创建轻量模板。关键区别在于前者保留历史记录和分层,后者生成单层镜像。save/load命令示例:docker save -o nginx.tar nginx:latest,export/import示例:docker export -o container.tar abc123 && docker

weixin_39291964的博客 882

Unity 面试篇|(六)数据结构和算法篇 【全面总结 | 持续更新】

先拿10000个数建堆,然后一次添加剩余元素,如果大于堆顶的数(10000中最小的),将这个数替换堆顶,并调整结构使之仍然是一个最小堆,这样遍历完后,堆中的10000个数就是所需的最大的10000个。桶排序是计数排序的升级版。它的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。这样处理就可以分别在每个文件的10^6个数据中找出最大的10000个数,合并到一起在再找出1000*10000中的最终的结果。

游戏开发小Y的博客 12万+

Vector源码解析

Vector源码解析 继承接口 继承了 AbstractList 类,这个类也实现了 List 方法 实现了 Serializable ,能进行序列化操作 实现了 Cloneable 接口,能够使用 clone() 方法 实现了RandomAccess,说明 Vector 也支持随机访问,在 Vector 中,可以通过元素的索引快速获取元素对象,这就是快速随机访问。 成员变量 // 存储数据的数组,此数组的容量一般大于实际长度,后续未填充数据用 null 替代 protected Object[]

qq_50596778的博客 418

【WorkBuddy专栏19】技能的创造与迁移——从零开始打造你的AI工作流

【WorkBuddy专栏19】技能的创造与迁移——从零开始打造你的AI工作流

AI人人懂 396

Vector源码深度解析以及应用介绍

基于JDK1.8对Java中的Vector集合的源码进行了深度解析,包括各种方法、特有的Enumeration迭代器机制,并且给出了Vector和ArrayList的区别以及使用建议。

终生学习践行者 2915

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

vector源码解析

1、vector源码解释与测试 调试环境采用的是VS2015,大家可以选择自己合适的编译环境去调试。 myVector.h #ifndef MY_VECTOR_H #define MY_VECTOR_H #define _SCL_SECURE_NO_WARNINGS #include <memory> #include <iostream> #include <a...

小麦大大博客 470

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Vector标签解析

Vector使用前言如果要说Vector,就不得不提SVG了,首先,需要讲解两个概念——SVG和Vector。SVG,即Scalable Vector Graphics 矢量图,这种图像格式在前端中已经使用的非常广泛了。Vector,在Android中指的是Vector Drawable,也就是Android中的矢量图,因此,可以说Vector就是Android中的SVG实现,因为Android中的

HardWorkingAnt的博客 1754

Vector类源码解析

Vector特点: 1.内部通过数组实现 2.通过synchronized同步方法,线程安全,适合多线程 3.由于线程安全,效率不高 4.默认存放10个元素 所在包package java.util;继承AbstractList 实现List 、RandomAccess、Cloneable、java.io.Serializable Clone: 简单的说就是clone一个对象实例。使

水滴石穿 2041

vector详细解析

当n大于size,会自动扩容,使size的大小为n,扩大capacity,尾部添加默认值0,也可以自己手动修改默认值。逆向迭代器,rbegin()指向最后一个元素的逆向迭代器,rend()指向第一个元素之前的位置的逆向迭代器,若容器为空则rbegin()==rend()。begin()用于获取指向容器第一个元素的迭代器,若容器为空,则begin()==end();清空所有元素,使size()为0,但保留capacity()不变,不会释放底层内存。rbegin()与rend()begin()与end()

ccf3699f的博客 925

unity使用Netjson自定义向量Vector解析

Newtonsoft.Json.dll 以Vector2为例: 解析Vector2你可能会解析出:“x”:0,“y”:1之类不符合你预期的字符串。 自定义解析出来的规则(例:你希望解析规则是"(0,1)".而不需要X,Y或其他乱七八糟的元素) 1.定义一个类,重写: public class Vector2Converter : JsonConverter { public override bool CanConvert(Type objectType) { return

QiuUnity的博客 1242

Vector底层源码解析

Vector集合总结:Vector实现了List接口,Java1.0版本推出,底层也是一个Object数组elementData,与Arraylist不同的时,Vector是线程安全的,每个方法几乎都有synchronilzed关键字,所以在多线程的情况下,应该使用Vector集合。Vector的数组长度默认是10,满后按照2倍进行扩容,如果制定大小则直接按2倍扩容,除了线程安全和默认10容量与2倍扩容,几乎和Arraylist没有什么区别。提示:以下是本篇文章正文内容,下面案例可供参考集合体系继承图。

无奈朝来寒雨晚来风 的博客 767

STL容器解析之Vector

vector容器可以说是STL最基本的容器,其实现也可以说是最简单的,但是vector同时也是使用频率最高的STL容器。其实现的动态数组的效果可以广泛的应用在各个层面。 对于传统的数组(array),我们常常不得不因为无法知晓在运行期确定的元素个数而为其配置一个大块头,造成了严重的内存浪费。vector相比于传统数组的改进之处在于vector的空间可以自行扩展,且这种可以自行随着元素的加入,在内

J.的学习室 498

vector源码解析及扩容优化

介绍了vector的原理并分析了其源码,对vector扩容过程中的优化进行了讨论

mrqiuwen的博客 1502

c++ vector 初始化_集合源码解析之Vector

集合源码解析之Vector概述在前两章我们已经学习了List常用的两个实现ArrayList、LinkedList,下面我们来学习下Vector.Vector和ArrayList一样是基于数组实现的List,区别在于Vector是线程安全的,我们来研究下其源码.Vector和ArrayList配合食用,味道更佳哦…源码分析结构图 继承关系 publicclassVector<E...

weixin_39559119的博客 232
上一篇: 进程控制块PCB结构 task_struct 描述
下一篇: 关于STL中List解析
Csoul89757
博客等级 码龄11年 34粉丝 72原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值