Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ How to sort a vector of bitsets?

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?

like image 440
NPa Avatar asked Oct 23 '15 12:10

NPa


Video Answer


1 Answers

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::strings 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 longs instead of strings.

like image 97
NathanOliver Avatar answered Sep 20 '22 11:09

NathanOliver