I look up the boost's implementation of the dynamic_bitset
and find that they compares the underlying integer storage type to improve the operator<
performance, I test the correctness with following code and get the inconsistent result. Is this a bug?
std::vector<bool> v1, v2;
v1.push_back(0); v1.push_back(1);
v2.push_back(1); v2.push_back(0);
std::cout << (v1 < v2) << '\n';
boost::dynamic_bitset<> b1, b2;
b1.push_back(0); b1.push_back(1);
b2.push_back(1); b2.push_back(0);
std::cout << (b1 < b2) << '\n';
I expect the output of both to be 1
, but the second output is 0
.
Look at the bitset from most significant bits to the least significant ones
#include <iostream>
#include <boost/dynamic_bitset.hpp>
int main(int, char*[]) {
boost::dynamic_bitset<> x(5); // all 0's by default
x[0] = 1;
x[1] = 1;
x[4] = 1;
std::cout << x << "\n";
return EXIT_SUCCESS;
}
The output is
10011
The operator<<
for dynamic_bitset
prints the bitset from most-significant to least-significant, since that is the format most people are use to reading.
And this is what you are doing
b1.push_back(0); b1.push_back(1);//b1 = 10
b2.push_back(1); b2.push_back(0);//b2 = 01
Boost is correct.
You should change the order of push_back
s to get what you intended.
Boost