关于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的一个集合类,它是线程安全的。 阅读详情

相关推荐

1006. 换个格式输出整数 (15)-PAT乙级真题

1006. 换个格式输出整数 (15)让我们用字母B来表示“百”、字母S表示“十”,用“12…n”来表示个位数字n(&lt;10),换个格式来输出任一个不超过3位的正整数。例如234应该被输出为BBSSS1234,因为它有2个“百”、3个“十”、以及个位的4。输入格式:每个测试输入包含1个测试用例,给出正整数n(&lt;1000)。输出格式:每个测试用例的输出占一行,用规定的格式输出n。输入样例1...

柳婼 の blog 2243

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

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

zqmgx13291的博客 1377

Anaconda启动失败,一直在loading application的问题

实战基础新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本

Tristan的博客 2771

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

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

qq_38409301的博客 226

(篇八)C语言在母串删子串、输入位置截取子串

文章目录一、字符串二、删除指定的字符三、从母串中截取子串四、输入位置截取子串 本篇主要介绍C语言字符串中的相关操作,然后分析两个C语言实例——在母串中指定删除子串、在母串中截取子串 一、字符串 了解C 语言的都知道,C语言中没有字符串类型,所以C语言是用字符串常量、字符指针、字符数组来表示字符串。这些字符串都是以 NULL、’\0’或者ASCII==0来结尾。说白了就是一个个字符组成一串有序序列,...

Viewinfinitely的博客 1512

机器视觉学习(七)—— 卷积、边缘和滤波器

卷积运算、垂直边缘与水平边缘、滤波器

歆歆~黯了 2740

C++ vector 容器浅析

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

qq_45131570的博客 1310

《数据结构》04-树4 是否同一棵二叉搜索树

题目 给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都得到一样的结果。于是对于输入的各种插入序列,你需要判断它们是否能生成一样的二叉搜索树。 输入格式: 输入包含若干组测试数据。每组数据的第1行给出两个正整数N (≤10)和L,分别是每个序列插入元素的个数和需要...

叫我皮卡丘 2012

vector

vector详细介绍

m0_59278204的博客 330

SAP ABAP 获取采购订单未清数量/在途库存的 6 种方式

这篇文章我总结了获取采购订单未清数量/在途库存的 6 种方式,每种方式的优劣势和适用场景有所不同。读者请结合自身需要选择。

SAP李斌,本人承诺所有原创文章均不使用任何AI生成技术,请大家放心阅读。 2667

DeepSeek掘金——用DeepSeek模型构建AI 代理

在本综合指南中,我们将探讨如何利用 DeepSeek 的功能构建能够以有意义的方式理解、推理和交互的复杂 AI 代理。人工智能领域正在迅速发展,DeepSeek 的模型代表了智能 AI 代理开发的重大进步。在本综合指南中,我们将探讨如何利用 DeepSeek 的功能构建能够以有意义的方式理解、推理和交互的复杂 AI 代理。

3862

Vector源码解析

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

qq_50596778的博客 416

华为od 面试八股文_Python_05_含答案

华为od 面试八股文_Python_05_含答案

MISAYAONE的博客 2566

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

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

终生学习践行者 2914

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

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

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Vector标签解析

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

HardWorkingAnt的博客 1754

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

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没有什么区别。提示:以下是本篇文章正文内容,下面案例可供参考集合体系继承图。

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

STL容器解析之Vector

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

J.的学习室 498

vector源码解析及扩容优化

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

mrqiuwen的博客 1499

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
博客等级 码龄10年 34粉丝 72原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值