64,661
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <vector>
#include <iostream>
using std::cout;
using std::endl;
using std::vector;
template<typename ContainersType>
void printContainersData(ContainersType containers)
{
ContainersType::iterator begin = containers.begin();
ContainersType::iterator end = containers.end();
for (; begin!=end; begin++)
{
cout<<*begin<<' ';
}
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
//定义空Vector
vector<short>vContainers1;//vContainers1.capacity()结果为13 为什么?
//vector<short>vContainers1(4);//vContainers1.capacity()结果为19 为什么?
//vector<short>vContainers1(5);//vContainers1.capacity()结果为15 为什么?
//向Vector中输入元素
for (short index = 0; index<10; index++)
{
vContainers1.push_back(index);
}
cout<<"为空Vector赋值,结果为:\n";
cout<<"vContainers1:";
printContainersData(vContainers1);
cout<<vContainers1.capacity());//容器为空时capacity()不可控?
cout<<endl;
return 0;
}
再看看reserve:
177 void
178 reserve(size_type __n)
179 {
180 bool __realloc = _M_requires_reallocation(__n);
181 _Base::reserve(__n);
182 if (__n > _M_guaranteed_capacity)
183 _M_guaranteed_capacity = __n;
184 if (__realloc)
185 this->_M_invalidate_all();
186 }
lz看自己编译器的实现源码吧,我的gcc上如下:
73 explicit vector(const _Allocator& __a = _Allocator())
74 : _Base(__a), _M_guaranteed_capacity(0) { }
75
76 explicit vector(size_type __n, const _Tp& __value = _Tp(),
77 const _Allocator& __a = _Allocator())
78 : _Base(__n, __value, __a), _M_guaranteed_capacity(__n) { }
79
80 template<class _InputIterator>
81 vector(_InputIterator __first, _InputIterator __last,
82 const _Allocator& __a = _Allocator())
83 : _Base(__gnu_debug::__check_valid_range(__first, __last),
84 __last, __a),
85 _M_guaranteed_capacity(0)
86 { _M_update_guaranteed_capacity(); }
87
88 vector(const vector<_Tp,_Allocator>& __x)
89 : _Base(__x), _Safe_base(), _M_guaranteed_capacity(__x.size()) { }
90
91 /// Construction from a release-mode vector
92 vector(const _Base& __x)
93 : _Base(__x), _Safe_base(), _M_guaranteed_capacity(__x.size()) { }
94
95 ~vector() { }