I have a vector of bitsets
:
vector < bitset<1024> > myvector;
What is the best way to sort this vector from:
0: xxx0100
1: xxx1100
2: xxx0010
3: xxx0001
...
...
to this order:
0: xxx0001
1: xxx0010
2: xxx0100
3: xxx1100
...
...
I already tried to do this with std:sort, but it didn't work, because std:sort use the "<" - operator, which doesn't work for bitsets.
Thanks in advance for your help! Any suggestions or ideas are greatly appreciated!
EDIT:
My question is different to Sorting a vector of custom objects, because it is impossible to use "<"- operator for bitset
. So my question is, which operator can I use instead, to compare bitset
?
A simple way to sort a std::bitset
would be to convert it to a std::string
using std::bitset::to_string
and then use std::string
s operator<
to compare the bitsets.
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 into a unsigned long long
then you can use std::bitset::to_ullong
and compare the unsigned long long
s instead of strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With