我知道在 std::vector 中,每次空间用完时大小都会增加。然而,我没有注意到它的增长模式。有人可以向我解释一下这种模式以及为什么选择它。
#include <iostream>
using namespace std;
#include <iostream>
#include <vector>
int main()
{
vector<int> myVector;
for(int i =0 ; i < 100; ++i)
{
myVector.push_back(i);
cout << myVector.capacity();
cout << ", ";
}
}
结果:
1, 2, 3, 4, 6, 6, 9, 9, 9, 13, 13, 13, 13, 19, 19, 19, 19, 19, 19, 28, 28, 28, 2
8, 28, 28, 28, 28, 28, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 6
3, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 6
3, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 9
4, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 141, 141, 141, 141, 141, 141