迭代通过集合进入无限循环

问题描述 投票:0回答:1

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

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子集的总和。但不能正常工作..我不知道为什么..

c++11 for-loop iterator each
1个回答
0
投票

问题是你在迭代它时插入元素(使用ranged-for循环)。 ranged for for for循环语义不涉及在循环开始之前记住范围的状态;就像写作一样:

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

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

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

(另外,一般来说,你的所有代码似乎都有点怀疑,即我怀疑你真的想要首先做这些东西。)

© www.soinside.com 2019 - 2024. All rights reserved.