首页 > 解决方案 > 我可以使用 std::vector::insert 向自身插入一个向量吗?

问题描述

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());

或者

// 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());

标签: c++stdvectorc++03

解决方案


无论是否reserve提前执行,行为都是未定义的。对于std::vector::insert

在 pos 之前插入范围 [first, last) 中的元素。

如果 first 和 last 是迭代器,则行为未定义*this


推荐阅读