C++初阶-vector的底层

news2025/5/21 8:44:27

目录

1.序言

2.std::sort(了解)

3.vector的底层

3.1讲解

3.2构造函数

3.3push_back函数

3.4begin()和end()函数

3.5capacity()和size()函数和max_size函数

3.5.1size()函数

为什么这样写?

底层原理

3.5.2max_size()函数

为什么这样写?

示例

3.5.3capacity()函数

为什么这样写?

与 size() 的区别

3.5.4总结

3.6operator[]函数

4.总结



1.序言

这讲将会补充一下之前的排序算法,这个算法是C++库里面实现的sort函数,后面将会分析一下vector的底层,之后将会有一定的看源码的过程,通过这些代码我们就可以来知道它如何实现的,方便下一讲将讲解的:vector的模拟实现。不过,在源码中实现的肯定是很严谨的,我们主要还是看一些比较重要的函数,没看懂的可以结合C++官方库来了解。

2.std::sort(了解)

首先使用该算法需要包含头文件:

<algorithm>

这个函数是专门进行排序的,默认排序是升序,我们可以传递一个迭代器区间,也可以传递一个数组的区间给这两个参数,如果想要排成降序,需要用到仿函数(即用第二个函数),这里只讲解一下其普通的用法:

#define _CRT_SECURE_NO_WARNINGS 1
#include<vector>
#include<iostream>
//算法的头文件
#include<algorithm>
using namespace std;
//std::sort函数的使用
int main()
{
	//这个构造函数的方式是从C++11开始有的,之前也没讲过
	vector<int> v = { 3,4,3,6,90,34,5,53,76,22,534,3434,64,22,56 };
	vector<int> v1 = { 3,4,3,6,90,34,5,53,76,22,534,3434,64,22,56 };
	//排成升序
	sort(v.begin(), v.end());
	for (const auto& d : v)
	{
		cout << d << " ";
	}
	cout << endl;
	//排成降序
	greater<int> gt;
	sort(v.begin(), v.end(), gt);
	for (const auto& d : v)
	{
		cout << d << " ";
	}
	cout << endl;
	//或者这样写
	//隐式类型转换
	sort(v1.begin(), v1.end(), greater<int>());
	for (const auto& d : v)
	{
		cout << d << " ";
	}
	cout << endl;
	return 0;
}

这个greater也是一个模板,我们现阶段只要知道基本用法即可,所以就不做过多讲解了!注:sort函数在list部分会进行更详细的讲解,这里只是简单介绍!!!

3.vector的底层

这是vector的实现的部分代码(不想看的可以直接到目录里面跳到3.1讲解里面):

/*
 *
 * 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

template <class T, class Alloc = alloc>
class vector {
public:
  typedef T value_type;
  typedef value_type* pointer;
  typedef const value_type* const_pointer;
  typedef value_type* iterator;
  typedef const value_type* const_iterator;
  typedef value_type& reference;
  typedef const value_type& const_reference;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;

#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:
  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() {
    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() : start(0), finish(0), end_of_storage(0) {}
  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) {
    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
  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) {
    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); }
  void push_back(const T& x) {
    if (finish != end_of_storage) {
      construct(finish, x);
      ++finish;
    }
    else
      insert_aux(end(), x);
  }
  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
  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;
  }
  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
  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 */
};

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 */

template <class T, class Alloc>
vector<T, Alloc>& vector<T, Alloc>::operator=(const vector<T, Alloc>& x) {
  if (&x != this) {
    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;
}

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 {
    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) {
  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:

3.1讲解

这个代码一共是有534行,我也不想把所有代码复制过来,但是CSDN上没有这个加入附件的功能:

所以我也没办法用附件的形式给出,这里就只能这样复制粘贴了。我们可以发现vector的实现还是比较复杂的,我们之后实现不会非常复杂,因为别人是考虑了很多情况才写这么多的,而且一堆的头文件,如果我们进入一个函数那么就会很难退出来,因为有不同的函数调用,我们在看源代码的时候就不需要全部看了,只要注意它如何实现的即可。

我将从几个比较重要的函数来进行讲解,其他的选择性讲解。

我们先看成员变量(63-66行):

typedef simple_alloc<value_type, Alloc> data_allocator;
iterator start;
iterator finish;
iterator end_of_storage;

第一行的那个typedef我们可以不用管,后面三个就是成员变量。

这个与我们之前在数据结构章节学习的capacity、str、size都不一样,这三个都是指针,我们可以看到第43-51行的一系列typedef,就得出了这个结论:

typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type* iterator;
typedef const value_type* const_iterator;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;

也就是说,iterator实际上是指针,所以我们可以说vector三个成员变量都是指针,也就是说它们都是需要解引用后才能得到那个位置的数据的。

我们可以通过这些变量的名字来得出它的指向,start指向开头,finish指向有效存储数据的结尾,end_of_storage指向能存储的最大元素的位置,这就相当于我们的capacity换为end_of_storage,而size换为finish了。用迭代器存储能保证存储的数据类型多样化,也满足了遍历。因为迭代器是通用的遍历方式。

3.2构造函数

我们可以在97-101行看到vector构造函数的声明:

vector() : start(0), finish(0), end_of_storage(0) {}
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()); }

这些函数几乎有一个共同点,调用了fill_initialize函数,那我们找一下这个函数的位置:

void fill_initialize(size_type n, const T& value) {
  start = allocate_and_fill(n, value);
  finish = start + n;
  end_of_storage = finish;
}

在第72-76行有这个函数的定义,我们发现又有一个函数:allocate_and_fill。那我们又需要查找这个函数:

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

在第213-220行找到该函数定义,到这个阶段,我们连代码都有些看不懂了,所以说我们没必要去带着目的去找这函数如何定义的,因为我们没办法理解每一个函数,所以只要看个大概就可以了,我们只要知道它到底是什么即可,我们可以通过那个无参的构造函数入手,加上其他的函数如push_back知道start是什么。

3.3push_back函数

在第144-151行发现了这个函数的定义:

void push_back(const T& x) {
  if (finish != end_of_storage) {
    construct(finish, x);
    ++finish;
  }
  else
    insert_aux(end(), x);
}

我们通过if-else语句得到,第一个肯定是直接插入x到finish位置,然后再把finish++这是大概操作,第二个则是先扩容,然后再把数据插到end()指向位置后,再把finish++,并把end_of_storage改为扩容后的大小,这是我们的想象的思路,那么真实情况是不是这样呢?

第一个construct函数我们是找不到的,应该需要其他的文件中有这个函数,不过这个不是重点,我们重点是看第二个函数,因为它肯定有construct函数的功能!

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

在322到356行找到该函数,可以了解到了,进入这个函数一定是在else语句中进行的,所以我们需要看else,但是又是这么多代码还是不知道,我们只看最后三行代码与我们猜想是不是一样的即可:

start = new_start;
    finish = new_finish;
    end_of_storage = new_start + len;

没有问题,我们的猜想是没有问题的,所以我们只需要这么多即可,前面都是判断条件,已经特殊情况处理。

3.4begin()和end()函数

要了解构造函数,也可以通过begin()和end()函数来知道每个成员变量的意思:

iterator begin() { return start; }
const_iterator begin() const { return start; }
iterator end() { return finish; }
const_iterator end() const { return finish; }

在第78行到81行找到了该函数的定义,我们也可以知道了:start一定是指向开始位置的迭代器,finish一定是指向结束位置的迭代器。所以我们可以知道其实每个构造函数初始化后它的start和finish指向的位置已经帮我们处理好了,所以我们就不需要管了。

3.5capacity()和size()函数和max_size函数

在90-92行找到三个函数:

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

首先看到size()函数在end()-begin()外面加了一个size_type,这个就是为了保证返回值一定为size_type类型,其他的函数也是一样的。我们可以通过deepseek的分析来得到结论:

3.5.1size()函数

为什么这样写?
  • end() - begin() 计算的是两个指针(迭代器)之间的元素个数,因为vector在内存中是连续存储的。

  • size_type 是无符号整型(如 size_t),确保返回值非负。

  • 这种写法:

    • 高效:直接计算指针差值,比维护一个单独的size变量更快。

    • 通用:适用于所有随机访问迭代器(如数组指针、vector迭代器等)。

    • 与STL设计一致:其他容器(如arraydeque)也可能用类似方式计算大小。

底层原理
  • begin() 返回指向第一个元素的指针。

  • end() 返回指向末尾后一位的指针(即最后一个元素的下一个位置)。

  • 指针相减的结果就是元素数量(因为sizeof(T)是固定的)。

3.5.2max_size()函数

为什么这样写?
  • size_type(-1) 是无符号整型的最大值(如 size_t 的最大值 0xFFFF...)。

  • 除以 sizeof(T) 表示当前类型T的理论最大可能元素数量(受限于内存地址空间和类型大小)。

  • 这种写法:

    • 平台无关:自动适配不同系统的地址空间(32位/64位)。

    • 类型安全:考虑到了T的大小,避免分配不合理的内存。

示例
  • 在64位系统中,size_t 最大值是 264−1264−1。

  • 如果 T 是 int(4字节),max_size() 返回 (264−1)/4(264−1)/4。

3.5.3capacity()函数

为什么这样写?
  • end_of_storage 是vector内部指向预分配内存末尾的指针(即当前分配的总空间边界)。

  • begin() 是数据起始指针,两者差值表示当前分配的总容量(以元素数量为单位)。

  • 这种写法:

    • 直接反映内存分配capacity() 返回的是实际分配的内存能容纳的元素数,而非当前存储的元素数(size())。

    • 高效:指针运算比查询额外变量更快。

与 size() 的区别
  • size():当前存储的元素数量(逻辑大小)。

  • capacity():预分配的内存可容纳的元素数量(物理上限)。

3.5.4总结

三个函数设计综合考虑了很多种情况,我们可以通过这三个函数的写法来优化我们的写法。

3.6operator[]函数

在94/95行找到两个函数的定义:

 reference operator[](size_type n) { return *(begin() + n); }
 const_reference operator[](size_type n) const { return *(begin() + n); }

其中reference又是什么?

 typedef T value_type;
 typedef value_type* pointer;
 typedef const value_type* const_pointer;
 typedef value_type* iterator;
 typedef const value_type* const_iterator;
 typedef value_type& reference;
 typedef const value_type& const_reference;
 typedef size_t size_type;
 typedef ptrdiff_t difference_type;

我们知道它是引用,也就是返回类型的引用(不知道说法正不正确),比如如果为int,就返回int类型的数据,而其他的基本上也就没什么好说的了。

4.总结

该讲主要是讲vector它最重要的底层结构,实际上vector的实现也不是很复杂(相对其他的容器),但是还是需要注意它的很多内容,它涉及到一些我们没有在成员函数中提到的函数,而且方式与我们之前在C语言阶段的实现方式是有一定的区别的,所以这需要自己看完后去钻研源代码,顺序表这种东西之后也会比较频繁的用到,比如:排序。这个基本上是用顺序表来实现的,也就是说后面的list等容器实现功能比较复杂,这个vector是线性结构,实现起来不是很难(只是代码量多了一些而已)。好了,下节将讲解vector的模拟实现了,喜欢的可以一键三连哦!下讲再见!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2380597.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言指针深入详解(五):回调函数、qsort函数

目录 一、回调函数 1、使用回调函数改造前 2、使用回到函数改造后 二、qsort使用举例 1、使用qsort函数排序整型数据 2、使用qsort排序结构数据 三、qsort函数模拟实现 结语 &#x1f525;个人主页&#xff1a;艾莉丝努力练剑 &#x1f353;专栏传送门&#xff1a;《…

数据结构进阶:AVL树与红黑树

目录 前言 AVL树 定义 结构 插入 AVL树插入的大致过程 更新平衡因子 旋转 右单旋 左单旋 左右双旋 右左双旋 实现 红黑树 定义 性质 结构 插入 实现 总结 前言 在学习了二叉搜索树之后&#xff0c;我们了解到其有个致命缺陷——当树的形状呈现出一边倒…

基于Spring Boot + Vue的教师工作量管理系统设计与实现

一、项目简介 随着高校信息化管理的发展&#xff0c;教师工作量管理成为教务系统中不可或缺的一部分。为此&#xff0c;我们设计并开发了一个基于 Spring Boot Vue 的教师工作量管理系统&#xff0c;系统结构清晰&#xff0c;功能完备&#xff0c;支持管理员和教师两个角色。…

完善网络安全等级保护,企业需注意:

在数字化转型加速的当下&#xff0c;网络安全成为企业发展的基石。网络安全等级保护作为保障网络安全的重要举措&#xff0c;企业必须高度重视并积极落实。以下要点&#xff0c;企业在完善网络安全等级保护工作中需格外关注&#xff1a; 一、准确开展定级备案 企业首先要依据相…

Trae 04.22版本深度解析:Agent能力升级与MCP市场对复杂任务执行的革新

我正在参加Trae「超级体验官」创意实践征文&#xff0c;本文所使用的 Trae 免费下载链接&#xff1a;Trae - AI 原生 IDE 目录 引言 一、Trae 04.22版本概览 二、统一对话体验的深度整合 2.1 Chat与Builder面板合并 2.2 统一对话的优势 三、上下文能力的显著增强 3.1 W…

OceanBase 开发者大会:详解 Data × AI 战略,数据库一体化架构再升级

OceanBase 2025 开发者大会与5月17日在广州举行。这是继 4 月底 OceanBase CEO 杨冰宣布公司全面进入AI 时代后的首场技术盛会。会上&#xff0c;OceanBase CTO 杨传辉系统性地阐述了公司的 DataAI 战略&#xff0c;并发布了三大产品&#xff1a;PowerRAG、共享存储&#xff0c…

ubuntu环境下 基于Python 打包的 批量命令行可视化操作工具 GUI

文章目录 一.需求&#xff1a;二.原理支撑&#xff1a;三.简单Demo四.封装成GUI1.依赖库2.代码 五.打包成可执行文件六.命令行的配置七.运行效果 一.需求&#xff1a; 作为测试工程师&#xff0c;为了到现场高效的调试&#xff0c;部署工作&#xff0c;需要一个可视化的工具&a…

谷歌宣布推出 Android 的新安全功能,以防止诈骗和盗窃

在上周二的 Android Show 上&#xff0c;也就是Google I/O 开发者大会之前&#xff0c;谷歌宣布了 Android 的全新安全和隐私功能。这些新功能包括对通话、屏幕共享、消息、设备访问和系统级权限的全新保护。谷歌希望通过这些功能保护用户免遭诈骗&#xff0c;在设备被盗或被攻…

Qt/C++编写音视频实时通话程序/画中画/设备热插拔/支持本地摄像头和桌面

一、前言 近期有客户提需求&#xff0c;需要在嵌入式板子上和电脑之间音视频通话&#xff0c;要求用Qt开发&#xff0c;可以用第三方的编解码组件&#xff0c;能少用就尽量少用&#xff0c;以便后期移植起来方便。如果换成5年前的知识储备&#xff0c;估计会采用纯网络通信收发…

Android trace presentFence屏幕显示的帧

Android trace presentFence屏幕显示的帧 presentFence &#xff1a;当帧成功显示到屏幕时&#xff0c;present fence就会signal。 FrameMissed/GpuFrameMissed/HwcFrameMissed表示上一次合成的结果&#xff0c;当SurfaceFlinger合成后显示到屏幕上&#xff0c;present fence就…

c++ 类的语法4

测试析构函数、虚函数、纯虚函数&#xff1a; void testClass5() {class Parent {public:Parent(int x) { cout << "Parent构造: " << x << endl; }~Parent() {cout << "调用Parent析构函数" << endl;}virtual string toSt…

NMOS和PMOS的区别

1 区分NMOS和PMOS&#xff1a;衬底箭头指向G级的是NMOS&#xff0c;衬底箭头背向G级的是PMOS 2 区分D和S级&#xff1a;针对NMOS&#xff0c;体二极管的正方向为S级&#xff1b;针对PMOS&#xff0c;体二极管正的方向为D级 3 区分电流方向&#xff1a;针对NMOS&#xff0c;电…

java云原生实战之graalvm 环境安装

windows环境安装 在Windows环境下安装GraalVM并启用原生镜像功能时&#xff0c;需要Visual Studio的组件支持。具体要点如下&#xff1a; 核心依赖&#xff1a; 需要安装Visual Studio 2022或更新版本&#xff0c;并确保勾选以下组件&#xff1a; "使用C的桌面开发"…

2025年电工杯新规发布-近三年题目以及命题趋势

电工杯将于2025.5.23 周五早八正式开赛&#xff0c;该竞赛作为上半年度竞赛规模最大的竞赛&#xff0c;因免报名费、一级学会承办等因素&#xff0c;被众多高校认可。本文将在从2025年竞赛新规、历史赛题选题分析、近年优秀论文分享、竞赛模板分析等进行电工杯备赛&#xff0c;…

替换word中的excel

PostMapping("/make/report/target/performance/first") public AjaxResult makeTargetReportFirst(RequestBody MakeReportDTO makeReportDTO) {Map<String, String> textReplaceMap new HashMap<>();// 替换日期LocalDateTime nowData LocalDateTime…

大模型服务如何实现高并发与低延迟

写在前面 大型语言模型(LLM)正以前所未有的速度渗透到各行各业,从智能客服、内容创作到代码生成、企业知识库,其应用场景日益丰富。然而,将这些强大的 AI 能力转化为稳定、高效、可大规模应用的服务,却面临着巨大的挑战,其中高并发处理能力和低响应延迟是衡量服务质量的…

OBS Studio:windows免费开源的直播与录屏软件

OBS Studio是一款免费、开源且跨平台的直播与录屏软件。其支持 Windows、macOS 和 Linux。OBS适用于&#xff0c;有直播需求的人群或录屏需求的人群。 Stars 数64,323Forks 数8413 主要特点 推流&#xff1a;OBS Studio 支持将视频实时推流至多个平台&#xff0c;如 YouTube、…

经典面试题:TCP 三次握手、四次挥手详解

在网络通信的复杂架构里&#xff0c;“三次握手”与“四次挥手”仿若一座无形的桥梁&#xff0c;它们是连接客户端与服务器的关键纽带。这座“桥梁”不仅确保了连接的稳固建立&#xff0c;还保障了连接的有序结束&#xff0c;使得网络世界中的信息能够顺畅、准确地流动。 在面…

高光谱数据处理技术相关

一、Savitzky-Golay(SG)平滑 1. 基本概念 Savitzky-Golay(SG)平滑是一种基于局部多项式拟合的卷积算法,主要用于信号处理(如光谱、色谱数据)的去噪和平滑。其核心思想是通过滑动窗口内的多项式拟合来保留信号的原始特征(如峰形、宽度),同时抑制高频噪声。 2. 技术原…

机器视觉的PVC卷对卷丝印应用

在现代工业制造领域&#xff0c;PVC卷对卷丝印工艺凭借其高效、灵活的特点&#xff0c;广泛应用于广告制作、包装印刷、电子产品装饰等多个行业。然而&#xff0c;在高速连续的丝印过程中&#xff0c;如何确保印刷图案的精准定位、色彩一致性以及质量稳定性&#xff0c;一直是困…