打印整个数组而不是子集

Getting whole array printed instead of subsets

我使用了 i&(1< 时得到了正确的结果(给定数组的子集)

void subsets(int arr[], int n)
{
    for(int i=0;i<(1<<n);i++){
        for(int j=0; j<n; j++)
        {
            if(i&(1<<j)!=0)
            {
                cout<<arr[j]<<" ";
            }
        }
        cout<<endl;
    }
}
int main()
{
    int arr[3]={1,2,3};
    subsets(arr,3);
}

使用 clang++-Werror 标志构建时您的代码编译失败,我们将收到此错误:

operator_precendence.cpp:8:13: error: & has lower precedence than !=; != will be evaluated first [-Werror,-Wparentheses]
      if (i & (1 << j) != 0) {
            ^~~~~~~~~~~~~~~
operator_precendence.cpp:8:13: note: place parentheses around the '!=' expression to silence this warning
      if (i & (1 << j) != 0) {
            ^
              (            )
operator_precendence.cpp:8:13: note: place parentheses around the & expression to evaluate it first
      if (i & (1 << j) != 0) {
            ^
          (           )

所以很明显!=先被评估了,然后条件检查总是得到true。要修复它,我们只需要添加一个括号(编译器已经给了我们提示):

if ((i & (1 << j)) != 0) 或简单地使用 if (i & (1 << j))