我对 std::vector 的行为很好奇,但我在任何地方都找不到答案,所以......
让我们有一个奇怪的程序:
std::vector<int> vec;
vec.reserve(5);
for(int i = 0; i < vec.size(); ++i) // OK, I have noticed the mistake in the condition, I am leaving it here for educational purposes
{
vec.resize(vec.size() + 1);
vec[i] = 42;
}
内存分配方面的行为是什么?只有一次分配按预期保留内存,或者调整大小清除它不需要的内存?
最佳答案
对于初学者来说,这个循环永远不会执行
std::vector<int> vec;
vec.reserve(5);
for(int i = 0; i < vec.size(); ++i)
{
vec.resize(vec.size() + 1);
vec[i] = 42;
}
因为最初 vector 的大小等于 0。
也许你的意思是下面这样的
std::vector<int> vec;
vec.reserve(5);
for(int i = 0; i < vec.capacity(); ++i)
{
vec.resize(vec.size() + 1);
vec[i] = 42;
}
在这种情况下,不会重新分配 vector 。:)
这是一个演示程序
#include <iostream>
#include <vector>
int main()
{
const size_t N = 5;
std::vector<int> v;
v.reserve( N );
std::vector<int>::size_type i = 0;
do
{
v.resize( v.size() + 1);
std::cout << v.capacity() << '\t' << v.data() << std::endl;
} while ( ++i < v.capacity() );
return 0;
}
它的输出可能看起来像
5 0x824da10
5 0x824da10
5 0x824da10
5 0x824da10
5 0x824da10
关于调整保留 std::vector 大小时的 C++ 内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39273469/