vector 源码

【Java集合源码剖析】Vector源码剖析 Vector简介 Vector也是基于数组实现的,是一个动态数组,其容量能自动增长。 LinkedList是JDK1.0引入了,它的很多实现方法都加入了同步语句,因此是线程安全的(其实也只是相对安全,有些时候还是要加入同步语句来保证线程的安全),可以用于多线程环境。 LinkedList没有丝线Serializable接口,因此它不支持序列化,实现了Cloneable接口,能被克隆,实现了RandomAccess接口,支持快速随机访问。 Vector源码剖析 Vector的 阅读详情
// Filename:    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);  
  

  
  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);  
  }  
  
 
  
  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;  
  }  
  
  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;  
  }  
}  
   
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_NAMESPACE  
  
#endif /* __SGI_STL_INTERNAL_VECTOR_H */  
  
// Local Variables:  
// mode:C++  
// End:  

Vector源码解析 Vector源码解析1. Vector概述及继承体系 Vector 类可以实现可增长的对象数组。与数组一样,它包含可以使用整数索引进行访问的组件。与新 collection 实现不同,Vector 是同步的。 看一下Vector的继承体系:public class Vector<E>extends AbstractList<E> implements List<E>, Rando 阅读详情

相关推荐

c++stl vector源码简析

c++stl vector源码简析vector是我们经常用的容易之一,我们现在来简单看一下vector的部分源码理解vector的行为以便我们在使用过程中更得心应手首先看一下vector的alloc基类:template <class _Tp, class _Allocator, bool _IsStatic> class _Vector_alloc_base { public: typedef

Mimahoo的博客 1637

【C++从0到王者】第十三站:vector源码分析及手把手教你如何写一个简单的vector

手把手教你写一个vector

青色_忘川的博客 2323

vector源码

vector 源码// Filename: stl_vector.h /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentat

philips的专栏 1万+

Vector类源码详解

一、源码分析 1.继承的父类&实现的接口 public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable 继承了AbstractList类(继承后可以使用迭代器遍历), 实现了RandomAccess(标记接口,标明实现该接口的list支持快速随机访问), cloneable接口(标识接

LYQ20010417的博客 1093

Vector实现原理源码分析

Vector在jdk1.0版本就存在的一个并发列表类,Vector和ArrayList实现了非常相似的接口,集成了相同的类。和ArrayList不同的是,Vector是线程安全的,大部分的对外暴露的公共方法上,都添加了synchronized同步锁,很显然,同步锁的加入,使得Vector的性能并不高,要使用线程安全的List,则推荐CopyOnWriteArrayList。 一、Vector的类结构 从类的结构图看,Vector的类结构体系基本和ArrayList一致。 二、源码分析 /** * 存储元

HYM BLOG 1966

vector 的 CCP 源码

vector 公司网上的 ccp 源码,协议文档,样例和 canape

vector源码剖析

vector前导准备源码位置 * C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include源码版本 Copyright (c) 1992-2009 by P.J. Plauger. ALL RIGHTS RESERVED. Consult your license regarding permissions and rest

飞鸟的专栏 3294

Vector CCP协议实现C源码

Vector CCP协议实现源码,ASAM CCP 2.1 Specification,Reference Documentation for the CCP Driver

vector源码以及实例

/* vector与array数组比较类似 但是array是静态空间,一旦配置了空间就不能够再改变 vecotr是动态空间,随着元素的加入,它的内部机制就会自行扩充空间来容纳新的元素 //下面将真是vector函数的具体实现 //vector是一个连续的线性空间 */ //alloc是SGI的空间配置器 template <class T,Alloc=alloc> class vect...

Zyong139064359的博客 711

H3C设备VRF配置实战:5步搞定多业务网络隔离(附排错技巧)

本文详细介绍了在H3C设备上配置VRF(虚拟路由转发)实现多业务网络隔离的实战方法。通过五步配置流程,从创建VPN-instance、绑定接口到配置独立路由表,帮助网络工程师在单台设备上构建逻辑隔离的企业级网络,并分享了高级路由配置与常见排错技巧。

gold8的专栏 936

X光安检模型训练第一步:手把手教你处理OPIXray和HIXray这两个小众数据集

本文详细解析了X光安检AI模型训练的关键步骤,重点介绍如何处理OPIXray和HIXray这两个专业数据集。从数据格式转换到YOLO标准,再到数据增强和质量验证,手把手指导开发者高效利用这些数据集进行目标检测模型训练,提升安检场景下的危险物品识别准确率。

weixin_32629853的博客 316

C++ - 浅看vector源码

本文分析了SGISTL 3.0中vector源码的核心实现。主要关注stl_vector.h文件,重点解析了三个关键成员变量(start、finish、end_of_storage)的关系,它们分别表示有效数组区间起始、结束和存储空间末尾。文章通过构造函数和push_back函数示例,展示了vector的空间管理和扩容机制,强调未初始化空间需使用定位new操作。此外,还介绍了阅读源码的三个关键步骤:理解功能需求、梳理类框架结构和绘制类关系图,为源码阅读提供了方法论指导。

Distinguished_z的博客 1241

基于STM32的智能衣柜系统开发实战(附完整源码与硬件设计)

本文详细介绍了基于STM32的智能衣柜系统开发实战,包括硬件设计、软件架构和云端功能实现。系统具备实时温湿度监控、自动加热除湿、紫外线杀菌等核心功能,通过STM32F103C8T6主控芯片和ESP8266无线模块实现智能控制。附完整源码与硬件设计,适合科技爱好者和开发者参考。

peach的博客 780

Vector源码

Vector简介 public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable Vector是一个动态数组。 Vector继承了AbstractList,实现了List接口。 Vec...

weixin_42488905的博客 249

手把手教你用Microsoft AEC Challenge数据集训练自己的回声消除模型(附完整代码)

本文详细介绍了如何使用Microsoft AEC Challenge数据集训练专业的回声消除模型,包括环境准备、数据清洗、模型架构设计、训练流程和实际部署注意事项。通过完整的代码示例和实战指南,帮助开发者快速掌握AEC技术,提升语音通信系统的回声消除效果。

weixin_27697385的博客 454

【VSCode】【Clangd】从零构建:基于LLVM/Clangd+MINGW+CMake的Windows高性能C/C++开发环境实战

本文详细介绍了如何在Windows平台搭建基于LLVM/Clangd+MINGW+CMake的高性能C/C++开发环境。通过VSCode配置Clangd语言服务器,结合MINGW提供的GCC工具链和CMake的跨平台构建能力,实现轻量级、高效率的开发体验。文章包含从环境准备到实战配置的完整指南,特别适合追求开发效率和跨平台兼容性的开发者。

weixin_28839629的博客 310

Java8源码-Vector

前几天学习了ArrayList源码和迭代器模式在ArrayList源码中的使用,今天开始学习Vector源码。参考的JDK版本为1.8。 相信大家对Vector的使用已经很熟悉了,它和ArrayList的最大的不同是它是线程安全的,这点在Vector源码中也有说明。Vector源码中注释有这么一句“Vector is synchronized. If a thread-safe impleme...

潘威威的博客 8712

预测股票价格趋势:使用MATLAB进行股票价格预测

通过收集股票数据、数据预处理、构建预测模型以及可视化结果,我们可以利用MATLAB强大的计算和分析功能来预测股票价格的走势。然而,需要注意的是,股票市场具有高度复杂性和不确定性,预测结果仅供参考,并不构成投资建议。然而,借助计算机编程和数据分析工具,我们可以利用历史股价数据来建立模型,并预测未来的股票价格走势。首先,我们需要获取股票的历史价格数据。完成模型的拟合后,我们可以使用该模型来进行未来股票价格的预测。最后,我们可以使用MATLAB的绘图功能将预测的股票价格与实际股票价格进行对比,并进行可视化展示。

2301_79326588的博客 1018

【C++】Vector的使用和源码解析

其实很早之前,我就有去看STL源码的想法了。只是一直没有一个好的机会。最久空闲时间比较多,也正是这样一个好机会去阅读源码。为了事半功倍,不走弯路,我在网上查了很多资料。目前来说,C++ STL的源码相关的中文书籍还停留在侯捷老师的2002年出版的STL源码剖析。虽然侯捷老师确实是非常厉害的,很有教学能力的一位C++老师,但是还是要提,在计算机技术日新月异的环境下,一本二十多年前的书籍确实已经有点落后了。

meeiuliuus的博客 1740

scratch绘制四个三角形 2024年6月中国电子学会 图形化编程 scratch编程等级考试二级真题和答案解析

​ scratch绘制四个三角形 一、题目要求 2024年6月电子学会图形化编程Scratch等级考试二级真题 1、准备工作 1.保留默认角色小猫; 2.添加背景Stars。 2、功能实现 1 .隐藏角色小猫,设置画笔裙始位置为(0,0),画笔颜色为黄色,画笔的粗细为5; 2. 点击绿旗,绘制如下图所示图形,三角形的边长为50。 二、案例分析 1、角色分析 角色:小猫 2、背景分析 背景:Stars背景 3、前期准备 1. 保留默认的小猫不变 ​

青少年编程学习指导 1716

内网渗透(二)之基础知识-工作组介绍

在一个大型单位里,可能有成百上千台计算机互相连接组成局域网,它们都会列在"网络"(网上邻居)内。如果不对这些计算机进行分组,网络的混乱程度是可想而知的 为了解决这一问题,产生了工作组( Work Group)这个概念。将不同的计算机按功能(或部 门)分别列入不同的工作组,例如技术部的计算机都列入"技术部"工作组、行政部的计算机都 列入"行政部"工作组。要想访问某个部门的资源,只要在"网络"里双击该部门的工作组名 就可以看到该部门的所有计算机了。相比不分组的情况,这样的情况有序得多(尤其对大型局域网来说)。

把自己活成一道光,因为你不知道,谁会借着你的光,走出了黑暗。请保持心中的善良,因为你不知道,谁会借着你的善良,走出了绝望。请保持你心中的信仰,因为你不知道,谁会借着你的信仰,走出了迷茫。请相信自己的力量,因为你不知道,谁会因为相信你,开始相信了自己.... 1219

[Java集合源码剖析] Vector 源码分析

转载自 https://blog.csdn.net/ns_code/article/details/35793865 前言 在学习了 ArrayList 源码之后, 应该学习 Vector 源码, 将两者进行比较, 这是一个比较常问的面试题. 如何找到Vector 源码 找到类 : 在 IDEA 中新建一个 Java 项目, 在 External Libraries 中, 点击 < 1.8...

mrbm_lj的博客 209

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

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...

小麦大大博客 468

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

Vector 源码阅读

Vector源码阅读 仅大致过了下,有问题的请指出,谢谢。 版本 1.8 介绍 属于废弃类,内部方法线程安全,原因:synchronized修饰。 属性 下述属性不像LinkedList和ArrayList使用transient修饰,但仍重写了writeObject()和readObject() protected Object[] elementData protected int elemen...

xl十一的博客 153

Vector源码阅读

Vector源码阅读(基于jdk1.8) 前几天看了ArrayList,今天再来看看Vector,这两个其实大同小异,基本结构都差不多,只是一些细节上有区别:比如线程安全与否,扩容的大小等,Vector的线程安全通过在方法是直接加synchronize实现。扩容默认扩大为原来的2倍。 还是先来看类的定义,搞清类的结构层次: 可以看到Vector继承了AbstractList,实现了List,Ran...

码奴生来就只知道前进 513
上一篇: 虚函数的限制
下一篇: C++ Primer 第15章例子-文本查询程序
Savitch
博客等级 码龄16年 84粉丝 130原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值