2

I am almost done with my code except I need help on two thing. Here is my code: Code. For the function below, I am trying to make it so that I can use the input of "n" to initialize my array, myBits, instead of a constant, which is currently 5.

My Other question is right below that. I am trying to switch all of the right most bits to "true". I wrote the for loop in "/* .....*/" but it doesn't seem to be working. Right above it, I do it long ways for C(5,4) ....(myBit[0] = myBit[1]....etc...... (I am using this to find r-combinations of strings).... and it seems to work. Any help would be appreciated!!

void nCombination(const vector<string> &Vect, int n, int r){

    bool myBits[5] = { false };  // everything is false now
        myBits[1] = myBits[2] = myBits[3] = myBits[4] = true;

/*  for(int b = n - r - 1; b = n - 1; b++){
        myBits[b] = true;  // I am trying to set the r rightmost bits to true
    }
*/  
    do  // start combination generator
    {
       printVector(Vect, myBits, n);
    } while (next_permutation(myBits, myBits + n));  // change the bit pattern
 }
  • Use `std::vector myBits(n, false)`. – PaulMcKenzie Dec 04 '14 at 21:49
  • Note that [variable length arrays are not part of standard C++](http://stackoverflow.com/q/21273829/1708801) an alternative is to use [std::vector](http://en.cppreference.com/w/cpp/container/vector) or [std::array](http://en.cppreference.com/w/cpp/container/array). – Shafik Yaghmour Dec 04 '14 at 21:49
  • What is wrong with my loop in order to set r number of rightmost bits to true?? – Not_NSA_I_Swear Dec 04 '14 at 22:03

2 Answers2

0

These are called variable length arrays (or VLAs for short) and they are not a feature of standard C++. This is because we already have arrays that can change their length how ever they want: std::vector. Use that instead of an array and it will work.

randomusername
  • 7,927
  • 23
  • 50
0

Use std::vector<bool>:

std::vector<bool> myBits(n, false);

Then you have to change your while statement:

while (next_permutation(myBits.begin(), myBits.end()));

You will also have to change your printVector function to take a vector<bool>& as the second argument (you won't need the last argument, n, since a vector knows its own size by utilizing the vector::size() function).

As to your program: If you're attempting to get the combination of n things taken r at a time, you will need to write a loop that initializes the last right r bools to true instead of hard-coding the rightmost 4 entries.

int count = 1; 
for (size_t i = n-1; i >= 0 && count <= r; --i, ++count)
     myBits[i] = true;

Also, you should return immediately from the function if r is 0.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45