Ash*_*Ash 4 c++ stl bitset c++11
如此处所述,std::bitset::operator^=返回*this.从与从运营商的"通常"的解释,如+=, |=, *=人们可以合理地假定给定的std::bitset实例(具有相同的尺寸)a和b,表达(a^=b).count() 将存储按位的结果XOR在操作a,并且count() 将返回在比特数a即被设置为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;
}
Run Code Online (Sandbox Code Playgroud)
输出是
a==111111
b==010001
(a xor b) to string==101110
(a xor b) count==6 //this is wrong!!!!! It should be 4...
Run Code Online (Sandbox Code Playgroud)
快速查看std::bitset(参见此处)的实现似乎表明返回的引用确实是对lhs对象的引用(a在我的示例中).那么......为什么会这样?
Max*_*hof 10
这与bitset无关.考虑以下代码:
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.
Run Code Online (Sandbox Code Playgroud)
您正在使用赋值运算符,因此您的变量/ bitset 每次都会更改.在你的情况下,第二个评估产生((a ^ b) ^ b),当然是原始的a(设置了6位).
| 归档时间: |
|
| 查看次数: |
140 次 |
| 最近记录: |