C++初阶-vector的底层
目录
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
#endiftemplate <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_SPECIALIZATIONtypedef 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_TEMPLATEStemplate <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;}elseinsert_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;}elseinsert_aux(position, x);return begin() + n;}iterator insert(iterator position) { return insert(position, T()); }
#ifdef __STL_MEMBER_TEMPLATEStemplate <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());elseinsert(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_TEMPLATEStemplate <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_TEMPLATEStemplate <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_ORDERtemplate <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_TEMPLATEStemplate <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_EXCEPTIONScatch(...) {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_EXCEPTIONScatch(...) {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;}elseinsert_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设计一致:其他容器(如
array
、deque
)也可能用类似方式计算大小。
-
底层原理
-
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的模拟实现了,喜欢的可以一键三连哦!下讲再见!