C ++ How to sort a bit vector?

I have a vector bitsets :

 vector < bitset<1024> > myvector; 

What is the best way to sort this vector from:

0: xxx0100
1: xxx1100
2: xxx0010
3: xxx0001



in this order:

0: xxx0001
1: xxx0010
2: xxx0100
3: xxx1100



I already tried to do this with std: sort, but that did not work, because std: sort uses the "<" - an operator that does not work for bits.

Thanks in advance for your help! Any suggestions or ideas are welcome!

EDIT:
My question is different from Sorting a vector of custom objects because it is not possible to use the <"operator for bitset . So my question is, which operator can I use instead to compare bitset ?

+5
source share
1 answer

An easy way to sort std::bitset is to convert it to std::string using std::bitset::to_string , and then use the std::string operator< to compare the bits.

 std::vector<std::bitset<128>> data = {1000,2000,80000,15,6000,2}; std::sort(data.begin(), data.end(), [](const auto & lhs, const auto & rhs) { return lhs.to_string() < rhs.to_string(); }); 

Live example

As pointed out in the comments, if the bitset is small enough to fit in an unsigned long long , then you can use std::bitset::to_ullong and compare the unsigned long long instead of strings.

+7
source

Source: https://habr.com/ru/post/1234365/


All Articles