【发布时间】:2009-10-10 04:38:13
【问题描述】:
考虑一下:
// set_iterator.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <set>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
set<int> a1;
set<int> a2;
a1.insert(3);
a1.insert(4);
a1.insert(5);
a2.insert(1);
a2.insert(2);
a2.insert(6);
set<int>::iterator iter;
int x = 0;
for (iter = a1.begin(); iter != a1.end(); ++iter)
{
if (x == 0) {
x = 1;
a1.insert(a2.begin(), a2.end());
}
cout << *iter << endl;
}
system("pause");
return 0;
}
目标是只访问集合中的每个元素一次。我认为在我们将元素插入 a1 后迭代器无效。
输出是 3 4 5 6
1,2 不打印。
我们如何编码这种情况。
【问题讨论】:
-
我不明白你到底想做什么。为什么不先合并集合?
-
这只是一个例子。在迭代过程中,a1 的值可能会为 a2 生成必须添加到 a1 的值。并且必须将这些新值添加到 a1 中,并且每个这样的值都被访问以生成更多要访问的值。例如,我正在编写的简单 LR 解析器就是这种情况。