vector的实现

STL SGI 2.9.2版本源码中vector的实现细节。

insert(iterator position, size_type n, const T& x)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* 从position处(包括)开始插入n个相同的元素x
* */
template<class T, class Alloc>
void vector<T, Alloc>::insert(iterator position, size_type n, const T &x) {
if (n != 0) {
// end_of_storage表示可用空间的尾, finish表示未使用空间内存的起始处
// 可用空间个数大于等于n
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将迭代器first和last指定的范围内中的元素拷贝到以迭代器result起始的区域内
// 从finish - n 到finish(不包括finish)共有n个元素
uninitialized_copy(finish - n, finish, finish);
finish += n;

// 把[position, old_finish - n)中的元素拷贝到[old_finish - n - position, old_finish)指定的范围内
copy_backward(position, old_finish - n, old_finish);
fill(position, position + n, x_copy);
} else {
// 插入点之后的现有元素个数小于新增元素个数
// 为以finish开始的内存空间指定n-elems_after个x_copy的初值
// 返回值:被赋值的尾元素下一位置的迭代器
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);
}

// 如有异常发生,实现"commit or rollback" semantics
# 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;
}
}
}

向可变数组中position指定的位置之后加入n个元素x_copy。

插入点之后的元素个数大于等于新增元素个数n

插入点之后的元素个数大于等于新增元素个数n即size_type(end_of_storage - finish) >= n。

n=3,elems_after=7,x_copy = 17。

假设vector的当前状态如下:

a1

执行uninitialized_copy(finish - n, finish, finish);之后

a2

执行finish += n;之后,

a3

执行copy_backward(position, old_finish - n, old_finish);之后,

a4

执行fill(position, position + n, x_copy);之后,

a5

插入点之后的元素个数小于新增元素个数n

插入点之后的元素个数小于新增元素个数n即size_type(end_of_storage - finish) < n。

n=3, elems_after = 2, x_copy = 17。

假设vector的当前状态为:

1

执行uninitialized_fill_n(finish, n - elems_after, x_copy);后的状态:

22

执行finish += n - elems_after;后

31

执行uninitialized_copy(position, old_finish, finish);后

3

执行finish += elems_after;后

51

执行fill(position, old_finish, x_copy);后

61