-3

I am new in c++ and i have some difficulties to understand bitmask. If someone could describe in the simplest way how the following code work (http://rosettacode.org/wiki/Combinations#C.2B.2B):

#include <algorithm>
#include <iostream>
#include <string>

void comb(int N, int K)
{
    std::string bitmask(K, 1); // K leading 1's
    bitmask.resize(N, 0); // N-K trailing 0's

    // print integers and permute bitmask
    do {
        for (int i = 0; i < N; ++i) // [0..N-1] integers
        {
            if (bitmask[i]) std::cout << " " << i;
        }
        std::cout << std::endl;
    } while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}

int main()
{
    comb(5, 3);
}

I understand the purpose of this code and what is the output but i don't undertstand the initialization of the string bitmask std::string bitmask(K, 1), and what the resize(N, 0) do.

skualito
  • 87
  • 7
  • Just read the documentation of such functions on a site like *cppreference*. This is a basic skill that you'll need; SO does not need a question about every basic use of every function. – underscore_d Nov 16 '17 at 11:01
  • @underscore_d the purpose of this site is not to help ? i read the doc of this functions but i don't understand all the things, this is why i asked for explanations. no need to be so agressive... – skualito Nov 16 '17 at 13:20

1 Answers1

1

std::string bitmask(K, 1) creates a string called bitmask, and initialises it with K instances of the char 1 (note, not the char '1').

The bitmask.resize(N, 0) then resizes the string to be of size N, and fills any gaps with the char 0 (again, note not the char '1')

So if 'K' were 2 and N were 5, you'd end up with a string containing the non-printable characters 1 1 0 0 0

There are a few issues with the code as it appears to me - first of all, the constructor and resize should be passed '0' and '1', not 0 and 1. Secondly, it doesn't cater for when N is less than K

Steve
  • 1,747
  • 10
  • 18
  • ok and then `prev_permutation` loop over all permutation: `1 1 0 0 0`, `1 1 1 0 0`, .... and after we output `i` only when char is 1 ? – skualito Nov 16 '17 at 13:41
  • i presume it is a more efficient method than just use vector or array ? or the person did that just for the style ? :) – skualito Nov 16 '17 at 13:43