Reputation: 5
I want to sort a vector of bools by their value. This is the list:
std::vector<bool> bolis {true true false true false false true true};
Is there some kind of function that would make this list equal to this:
{true,true,true,true,true,false,false,false}
I saw the std::sort
function but it seems the only real use of it is to sort a list of ints or floats and not a list of bools.
Upvotes: 0
Views: 390
Reputation: 6494
The std::partition
function from the standard library is designed for doing exactly what you want to do. It accepts a range and a predicate, and reorders the elements of the range so that they are partitioned according to this predicate:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<bool> bolis {true, true, false, true, false, false, true, true};
//reorder so that true comes first
std::partition(bolis.begin(), bolis.end(), [](bool b){return b;});
std::cout << std::boolalpha;
std::copy(bolis.begin(), bolis.end(), std::ostream_iterator<bool>(std::cout, " " ));
return 0;
}
Output:
true true true true true false false false
Here's a demo.
Upvotes: 0
Reputation: 5311
First Method:
This can be achieved by defining the custom comparator function and passing it to the sort
function.
Have a look at the implementation as follows:
#include <iostream>
#include <vector>
#include <algorithm>
//define the function:
bool comparator(bool lhs, bool rhs) { return rhs < lhs; }
int main()
{
std::vector<bool> bolis {true, true, false, true, false, false, true, true};
// pass it to sort:
sort(bolis.begin(), bolis.end(), &comparator);
for(int i=0;i<bolis.size();i++){
std::cout<<(bolis[i] ? "true " : "false ");
}
std::cout<<std::endl;
}
Output:
true true true true true false false false
Second method in O(N) time complexity:
Count the number of true and false values in the vector and print them accordingly.
For example, if there are 5 true values and 2 false values, then print true for 5 number of number of times and false for 2 number of times.
Or you can push the values in another vector as well or edit the original vector.
Thanks to @john for all the suggestions to improve the answer!
Upvotes: 1
Reputation: 20141
To sort a std::vector<bool>
is a very specific case, and can be done by a very specific solution:
counting the number of true
elements and then rewrite the vector based on this count.
Sample code:
#include <vector>
#include <iostream>
int main()
{
std::vector<bool> bolis {true, true, false, true, false, false, true, true};
// count number of true
size_t nT = 0;
for (bool value : bolis) nT += value == true;
// write sorted vector
for (size_t i = 0, n = bolis.size(); i < n; ++i) bolis[i] = i < nT;
// show result
const char *sep = "";
for (bool value : bolis) {
std::cout << sep << std::boolalpha << value;
sep = ", ";
}
}
Output:
true, true, true, true, true, false, false, false
Upvotes: 1