c++ - 我可以使用 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());
解决方案
无论是否reserve
提前执行,行为都是未定义的。对于std::vector::insert
:
在 pos 之前插入范围 [first, last) 中的元素。
如果 first 和 last 是迭代器,则行为未定义
*this
。
推荐阅读
- android - org.gradle.api.tasks.TaskExecutionException:任务':walletlink:kaptDebugKotlin'的执行失败
- node.js - 错误:EROFS:只读文件系统,打开“metadata.json”。=> 我使用了 Firebase 函数。我部署了 json 文件。我不能写那个json
- arrays - 如何将 chars 数组与 C++ 中的 char 进行比较?为什么不这样工作?
- javascript - 如何使用javascript使随机图像可点击到专用页面?
- mips - MIPS:带分支的无限循环
- c# - 在数组上使用 AnyAsync()
- python-3.x - 将 CSV 文件拆分为两个文件,在两个文件中保留标题
- python - 根据规则对字符串列表求和
- python - 如何正确引发此异常?
- spring-boot - 使用 Oracle 的 Spring Boot 应用程序 - ORA-01000:使用 Spring Jdbctemplate 时超出最大打开游标