c++ - C++ 中嵌套增强型 for 循环的范围

标签 c++ foreach powerset

这是我的代码,用于生成集合的幂集,但它无法按预期工作。

#include <string>
#include <stdio.h>
#include <vector>

using namespace std;

vector<vector<int>> powerSet(vector<int> set){
    vector<vector<int>> result;
    vector<int> emptySet;
    result.push_back(emptySet);

    for(int i: set){
        for(vector<int> subSet:result){
            subSet.push_back(i);
            result.push_back(subSet);
        }
    }

    return result;
}

int main(){
    vector<int> a = {1, 2, 3};
    vector<vector<int>> r = powerSet(a);

    for(vector<int> v: r){
        for(int n : v){
            printf("%d ", n);
        }
        printf("\n");
    }
    return 0;
}

此代码打印:

1
2
2
3
3
3
3

稍微修改一下就可以了。这是我的工作代码:

#include <string>
#include <stdio.h>
#include <vector>

using namespace std;

vector<vector<int>> powerSet(vector<int> set){
    vector<vector<int>> result;
    vector<int> emptySet;
    result.push_back(emptySet);

    for(int i: set){
        vector<vector<int>> moreSets; // here is the changes
        for (vector<int> subSet: result){
            subSet.push_back(i); 
            moreSets.push_back(subSet); // here is the changes
        }
        result.insert(result.end(), moreSets.begin(), moreSets.end()); // here is the changes        }

    return result;
}

int main(){
    vector<int> a = {1, 2, 3};
    vector<vector<int>> r = powerSet(a);

    for(vector<int> v: r){
        for(int n : v){
            printf("%d ", n);
        }
        printf("\n");
    }
    return 0;
}

有人能告诉我第一个代码的问题是什么吗?太感谢了!

最佳答案

在第一个代码中查看以下代码

for(vector<int> subSet:result){
    subSet.push_back(i);
    result.push_back(subSet);
}

您正在更改正在迭代的结果。这不会有好的结果,甚至可能导致无限循环、程序崩溃等。

Range-based for loopbegin(container)end(container) 之间进行迭代,它们是通过依赖于参数的查找找到的(不执行非 ADL 查找)。

如果您更改loop_statement中的容器,则先前的(内部使用的)迭代器将无效,从而导致未定义的行为。

更多详情请阅读6.5.4 基于范围的for语句[stmt.ranged]


相关帖子:Erasing an element from a container while inside a range-based for loop

关于c++ - C++ 中嵌套增强型 for 循环的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27773562/

相关文章:

php - MySQL - 通过一组数字的所有组合查找具有逗号分隔值的字段

c++ - 输出冗余

C++ 嵌套 for 循环和中断

c++ - 使用C++ 11基于范围的正确方法是什么?

c# - 迭代变量如何只读?

java - 破解编码面试 : Why does the recursive subset algorithm increase the index rather than decreasing it?

c++ - g++ 模板名称修改

c++ - 为什么全局数组大小应该是整数常量?

php - 使用foreach循环传递两个变量

Java:生成幂集