遍历一个集合进入无限循环

iterate through a set goes to infinite loop

我在我的两个文件中使用了完全相同的代码。 一个正常工作,而另一个(这个)进入无限循环。

int arr[5] = {3, 1, 3, 5, 6};
int main() {
    int T = 1; 
    set<int> s;
    for (int tc = 0; tc < T; tc++) {
        s.emplace(0);
        for (auto x : arr) {
            auto end = s.end();
            for (auto it = s.begin(); it != end; it++) {
                // here's where goes to infinite loop
                // and i couldn't figure out why..
                s.emplace(*it+x); 
            }
        }
    }
    return 0;
}

下面一个是很好用的

using namespace std;

int main() {
    int arr[5] = {3,1,3,5,6}, sum=20;
    set<int> s;
    s.emplace(sum);
    for (auto x : arr) {
        auto end = s.end();
        for (auto it = s.begin(); it != end; it++) {
            s.emplace(*it-x);
        }
    }
    return 0;
}

预期结果是 s = {1, 4, 7, 8, ...} arr 的所有子集的所有总和。 但是不能正常工作..我不知道为什么..

问题是您在遍历集合时将元素插入集合(使用范围循环)。 ranged-for 循环语义不涉及记住循环开始前范围的状态;就像写作一样:

for(auto it = std::begin(container); it < std::end(container); it++)

现在,std::set 是一个 有序 容器。因此,当您 insert/emplace 个元素 比您的迭代器指向的元素小 时,您将不会在以后的迭代中看到它们;但是如果您插入 更大的 元素,您 看到它们。所以你最终只会无限地迭代你插入的元素。

你可能应该做的是 不是 在迭代期间将新元素放入 s 中,而是将它们放在其他容器中,然后最终转储所有元素将新容器的内容放入集合中(例如,std::inserter 到集合和 std::copy)。

(另外,总的来说,您的所有代码似乎都有点可疑,也就是说,我怀疑您一开始真的想做任何这些事情。)