Does std::vector::insert() invalidate iterators if the vector has enough room (created through reserve)?(如果向量有足够的空间(通过保留创建),std::vector::insert() 是否会使迭代器无效?)
问题描述
回答 如何自行复制向量? 让我明白了对迭代器失效有点困惑.一些文献说如果您使用 insert、push_back 等,请考虑所有迭代器无效".很明显,它可能会导致向量增长,从而使迭代器无效.我知道会有足够空间的特殊情况呢?
Answering How to self-copy a vector? has got me a bit confused about iterator invalidation. Some literature says "if you use insert, push_back, etc. consider all iterators invalid". Thats clear, it might cause the vector to grow which invalidates iterators. What about the special case where I know there is going to be enough room?
第一次尝试:
myvec.reserve(myvec.size()*3); //does this protect me from iterator invalidation?
vector<string>::iterator it = myvec.end();
myvec.insert(myvec.end(), myvec.begin(), it);
myvec.insert(myvec.end(), myvec.begin(), it);
在一些优秀的答案后第二次尝试:
After some excellent answers second try:
auto size = myvec.size();
myvec.reserve(size*3); //does this protect me from iterator invalidation?
myvec.insert(myvec.end(), myvec.begin(), myvec.begin()+size);
myvec.insert(myvec.end(), myvec.begin(), myvec.begin()+size);
经过更优秀的答案第三次尝试:
After more excellent answers third try:
auto size = myvec.size();
myvec.reserve(size*3); //does this protect me from iterator invalidation?
back_insert_iterator< vector<string> > back_it (myvec);
copy (myvec.begin(),myvec.begin()+size,back_it);
copy (myvec.begin(),myvec.begin()+size,back_it);
这句话来自 Josuttis 的C++ 标准库参考":
This quote from Josuttis' "C++ Standard Library Reference":
插入或删除元素使引用、指针和引用以下内容的迭代器元素.如果插入导致重新分配,它使所有引用、迭代器和指针.
Inserting or removing elements invalidates references, pointers, and iterators that refer to the following element. If an insertion causes reallocation, it invalidates all references, iterators, and pointers.
表明我的代码是安全且已定义的行为.标准中是否有段落可以保证这一点?
suggests that my code is safe and defined behavior. Is there a passage in the standard which guaranties this?
推荐答案
过去的迭代器总是有点特别.我会小心的.标准是这样说的(23.3.6.5):
The past-the-end iterator is always a bit special. I'd be careful. The standard says this (23.3.6.5):
如果没有发生重新分配,则插入点之前的所有迭代器和引用都保持有效.
If no reallocation happens, all the iterators and references before the insertion point remain valid.
这里的关键是在插入点之前".由于您的原始 it
不在插入点之前(因为它 是 插入点),我不会指望它保持有效.
The key here is "before the insertion point". Since your original it
is not before the insertion point (since it is the insertion point), I wouldn't bank on it remaining valid.
这篇关于如果向量有足够的空间(通过保留创建),std::vector::insert() 是否会使迭代器无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果向量有足够的空间(通过保留创建),std::vector::insert() 是否会使迭代器无效?
基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01