samedi 30 mars 2019

iterate through a set goes to infinite loop

i used exactly the same code in both of my files. and one is work properly while the other one (this one) goes to endless loop.

int N = 5;
int arr[5] = {3, 1, 3, 5, 6};
int main() {
    int T = 1, B = 16; 
    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;
}

below one is well working one

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;
}


expected results are s = {1, 4, 7, 8, ...} all the sum of all the subset of arr. but not working properly.. i don't know why..

Aucun commentaire:

Enregistrer un commentaire