2

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.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • 3
    @oblivion Where do you see pointers being used in this example? – Algirdas Preidžius Jun 13 '19 at 17:04
  • @AlgirdasPreidžius I was wrong. The comparison operator is defined `template bool operator<(const dynamic_bitset& a, const dynamic_bitset& b);` – Oblivion Jun 13 '19 at 17:09
  • @康桓瑋 If you're asking about a possible bug in `boost::dynamic_bitset`, you should add the exact version of `boost` and the compiler you use. Post a [mcve] as required here please. – πάντα ῥεῖ Jun 13 '19 at 17:09
  • Confirmed output of `1\n0` on boost 1.65.1 on my machine. Same output on 1.62.0 on [this online compiler](https://ideone.com/ravjVo). [The docs](https://www.boost.org/doc/libs/1_70_0/libs/dynamic_bitset/dynamic_bitset.html#op-less) says it should output `1`, the same as [`operator<` for `std::vector`](https://en.cppreference.com/w/cpp/container/vector/operator_cmp). – Artyer Jun 13 '19 at 17:18

1 Answers1

2

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_backs to get what you intended. Boost

Oblivion
  • 7,176
  • 2
  • 14
  • 33
  • Yep, you are right! I see the the document, they say "Effects: Increases the size of the bitset by one, and sets the value of the new most-significant bit to value." – 康桓瑋 Jun 13 '19 at 17:41
  • @康桓瑋 it looks a bit puzzling – Oblivion Jun 13 '19 at 17:48
  • 1
    @康桓瑋 bits are commonly numbered from least significant to most significant, so "back" of range is the most significant bit, that's natural. Bit 0 is 2^0, so its value is 1. – Swift - Friday Pie Aug 24 '19 at 09:39