在插入新元素时,我们如何遍历集合的所有元素?

Roh*_*nga 6 c++ stl

考虑一下:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

目标是访问集合中的每个元素一次.我认为在将元素插入a1后,迭代器无效.

输出为3 4 5 6

1,2不打印.

我们如何编码这样的情况.

rlb*_*ond 6

事实上,迭代器仍然有效.集合是基于节点的容器.

问题是在一个集合中,元素总是被排序.在插入之前,您的设置如下所示:

3 4 5
^
iter
Run Code Online (Sandbox Code Playgroud)

插入后,您的设置如下所示:

1 2 3 4 5 6
    ^
    iter
Run Code Online (Sandbox Code Playgroud)

如果您希望能够做您正在做的事情,您将不得不使用不同的容器.

  • 不是一套.考虑一个向量,您稍后将其排序并使用`std :: unique`和`std :: erase`. (3认同)