【发布时间】:2019-09-23 00:57:09
【问题描述】:
当我的代码在迭代时将元素插入 std::set 时,我发现了意外结果。我需要对此有所启发。
这里是测试代码:
template<class Ti, class T>
void iteration_insertion(Ti start, Ti end, T& S){
for (auto ite=start;ite!=end;++ite){
auto before=*ite;
if(*ite % 2)
S.insert(*ite*2);
else
S.insert(*ite/2);
if(before!=*ite)
cout<<before<<","<<*ite<<endl;
}
}
void test() {
set<int> S1({4,7,10,13}),S2(S1);
cout<<"ascending\n";
iteration_insertion(S1.begin(),S1.end(),S1);
cout<<"descending\n";
iteration_insertion(S2.rbegin(),S2.rend(),S2);
}
结果:
ascending
descending
13,26
我们可以看到迭代器指向的元素在插入后有时会发生变化。但我不知道什么时候会发生。在测试代码中它只发生了一次,降序为 13。为什么在升序迭代中没有这种不匹配?为什么在降序迭代中 7 没有不匹配?如何防止它发生?我很好,新的附加值可以在以后迭代,这是意料之中的。我只是不希望迭代器被插入改变。
测试代码可以是一种通用的启发式实践:从每个当前状态生成新状态以供进一步检查。
【问题讨论】:
-
感谢@chris 的回答,我想最简单的解决方案不是使用反向迭代器,而是使用 std::greater 作为比较器的前向