代码之家  ›  专栏  ›  技术社区  ›  Ash

对于STD:这是正常行为::BITSET::Trase^=和STD::BIT::计数?如果是,为什么?[关闭]

  •  4
  • Ash  · 技术社区  · 7 年前

    如文件所述 here , std::bitset::operator^= 收益率 *this . 从这个和从“通常”的解释,如 +=, |=, *= 人们可以合理地假设 std::bitset 实例(大小相同) a b ,表达式 (a^=b).count() 将按位存储结果 XOR 操作在 count() 将返回 设置为 true . 但是,正如下面的最小示例所示,会发生意外情况:

    #include <iostream>
    #include <bitset>
    
    int main()
    {
        constexpr unsigned int N=6; 
        std::bitset<N> a; 
        std::bitset<N> b; 
    
        a.flip();//111111
        b[0]=1;
        b[4]=1;//b is now 010001 (assuming least significan bit on the right end of the string)
    
        std::cout<<"a=="<<a.to_string()<<std::endl;
        std::cout<<"b=="<<b.to_string()<<std::endl;
        std::cout<<"(a xor b) to string=="<<(a^=b).to_string()<<std::endl;
    
        //Here is the unexpected part!
        std::cout<<"(a xor b) count=="<<(a^=b).count()<<std::endl;
        //Note that the following lines would produce the correct result
        //a^=b;
        //std::cout<<a.count()<<std::endl;
    
    
        return 0;
    }
    

    输出是

    a==111111
    b==010001
    (a xor b) to string==101110       
    (a xor b) count==6                //this is wrong!!!!! It should be 4...
    

    快速查看 STD::比特集 (见 here )似乎表明返回的引用确实是对lhs对象的引用( 在我的例子中)。所以…为什么会这样?

    1 回复  |  直到 7 年前
        1
  •  9
  •   Max Langhof    7 年前

    这与比特集无关。请考虑以下代码:

    int a = 2;
    int b = 3;
    std::cout << std::to_string(a *= b) << std::endl; // Prints 6.
    std::cout << std::to_string(a *= b) << std::endl; // Prints 18.
    

    您正在使用赋值运算符,因此您的变量/位集将更改 每一个 时间。在你的情况下,第二个评估结果 ((a ^ b) ^ b) ,当然是原件 a (设置了6位)。