首页 > 解决方案 > 打印整个数组而不是子集

问题描述

我使用了 i&(1<<j)!=0 以便在指定 true 或 false 的条件下得到 1 或 0,但我打印的是整个数组而不是子集。虽然我在使用 i&(1<<j) 时得到了正确的结果(给定数组的子集)。

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

标签: c++c++17bit-manipulation

解决方案


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))


推荐阅读