Fab*_*ian 3 c++ stdvector c++03
C++03 标准是否允许将 a 附加std::vector到自身?v我想知道如果需要重新分配内存,源迭代器是否会变得无效。在我的 STL 实现中,旧内存会一直保留,直到创建新内存为止。但我可以依靠这个吗?如果不是,v.reserve(2 * v.size())在插入之前是否是完全避免重新分配的良好解决方案?
vector<int> v;
v.reserve(3);
v.push_back(1);
v.push_back(2);
v.push_back(3);
// v may need to reallocate because its capacity may be less than 6.
// Is this operation safe?
v.insert(v.end(), v.cbegin(), v.cend());
Run Code Online (Sandbox Code Playgroud)
或者
// Here v will _not_ need to reallocate because it has enough capacity.
// Is this operation safe?
v.reserve(2 * v.size());
v.insert(v.end(), v.cbegin(), v.cend());
Run Code Online (Sandbox Code Playgroud)
无论是否reserve提前执行,行为都是未定义的。为了std::vector::insert:
在 pos 之前插入范围 [first, last) 中的元素。
如果第一个和最后一个是 的迭代器,则行为未定义
*this。