如何在将数据结构插入元素后继续迭代数据结构
How to keep iterating over data structure after inserting elements into it?
在下面的代码片段中,我将Instruction
插入到Function::iterator bs
指向的BasicBlock
中。内部循环遍历此BasicBlock
中包含的指令。
现在,在内部循环插入这些指令后,程序进入一个带有指令序列的无限循环:
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
...
如何插入正在迭代的数据结构中,同时避免进入无限循环?
不知何故,迭代器发疯了(或者它失效了(。如何解决这个问题有共同的成语吗?
for (Function::iterator bs = F.begin(), be = F.end(); bs != be; ++bs) {
for (BasicBlock::iterator is = bs->begin(), ie = be->end(); is != ie; ++is) {
Instruction& inst = *is;
BinaryOperator* binop = dyn_cast<BinaryOperator>(&inst);
if (!binop) {
continue;
}
unsigned opcode = binop->getOpcode();
errs() << binop->getOpcodeName() << "n";
if (opcode != Instruction::Add) {
continue;
}
IRBuilder<> builder(binop);
Value* v = builder.CreateAdd(builder.CreateXor(binop->getOperand(0), binop->getOperand(1)),
builder.CreateMul(ConstantInt::get(binop->getType(), 2),
builder.CreateAnd(binop->getOperand(0), binop->getOperand(1))));
ReplaceInstWithValue(bs->getInstList(), is, v); // THINGS GO WRONG HERE!
}
}
不幸的是,您未能提供足够的详细信息,但我强烈怀疑您将新元素插入容器的方式使现有迭代器(对其他元素(无效。这是许多容器类的常见行为,例如 std::vector<>::insert()
,如果新size()
迭代器超过 capacity()
,则所有现有迭代器无效(否则只有插入点之前元素的现有迭代器仍然有效(。
避免这种情况的方法是使用没有此问题的容器,例如std::list<>
,因为std::list<>::insert()
不会使任何现有的迭代器或引用无效。
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- C++中deque数据结构的大O是什么?
- 我可以使用哪种数据结构来处理这种方式
- 将文本文件解析为树状数据结构
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- 如何在将数据结构插入元素后继续迭代数据结构
- 现代C++.从继续执行的工作线程返回数据结构