Let's focus on the print problem of all subsets. As you know, if you have a vector of elements n
, you will have 2^n
possible subsets. It is no coincidence that if you have an n
bit integer, the maximum stored value is 2^n
. If you consider each integer as a vector of bits, then repeating all possible values โโwill give all possible subsets of bits. Well, we have subsets for free, iterating an integer!
Assuming that the vector contains no more than 32 elements (more than 4 billion possible subsets!), This code fragment will print all subsets of the vector v
(except for the empty one):
for (uint32_t mask =1; mask < (1<<v.size()); ++mask) { std::vector<int>::const_iterator it = v.begin(); for (uint32_t m =mask; m; (m>>=1), ++it) { if (m&1) std::cout << *it << " "; } std::cout << std::endl; }
I simply create all possible bit masks for the size of the vector and repeat each bit; if it is installed, I print the corresponding item.
Now applying the ending rule with some specific number is a piece of cake (by checking the additional state when passing through masks). Preferably, if your vector has only one 5 character, you can swap it to the end and print all subsets of the vector without the last element.
I use std::vector
, const_iterator
and std::cout
effectively, so you can think of it as a solution using STL. If I come up with something more STLish, I'll let you know (well, but how, it just repeats itself). You can use this function as a guideline for your STL solutions, but :-)
EDIT: As Jorgen Fogh noted, he does not solve your blues subtype if you want to work with large vectors. In fact, if you want to print all subsets for 32 elements, it will generate terabytes of data. You can use a 64-bit integer if you think that it is limited to a constant 32, but you would not even finish the iteration over all numbers. If your problem just answers how many desired subsets, you definitely need a different approach. And STL will also not be very useful; -)