Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your code is very close to correct, but the self-modifying <code>result</code> is going to be problematic. insertion into a vector does many things, among them invalidating iterators currently open on the sequence. But it will also change the result of <code>size()</code> (for obvious reasons, I hope).</p> <p>The simplest answer is to use a sub list vector, then enumerate <em>that</em>, appending all entries within with '0' and '1', and inserting those results into your return vector. An example of this is below:</p> <pre><code>std::vector&lt;std::string&gt; getBitStrings(unsigned int n) { std::vector&lt;std::string&gt; result; if (n &lt;= 1) { result.push_back("0"); result.push_back("1"); } else { // recurse, then add extra bit chars std::vector&lt;std::string&gt; sub = getBitStrings(n-1); for (std::vector&lt;std::string&gt;::const_iterator it = sub.cbegin(); it != sub.cend(); ++it) { result.push_back(*it+'0'); result.push_back(*it+'1'); } } return result; } </code></pre> <p>This is somewhat different than your implementation, in that it expects values between 1 and <code>n</code> for the bit count. Running with <code>n=5</code>, the following is produced:</p> <pre><code>int main() { std::vector&lt;std::string&gt; bs = getBitStrings(5); std::copy(bs.begin(), bs.end(), std::ostream_iterator&lt;std::string&gt;(std::cout, "\n")); return 0; } </code></pre> <p><strong>Output</strong></p> <pre><code>00000 00001 00010 00011 00100 00101 00110 00111 01000 01001 01010 01011 01100 01101 01110 01111 10000 10001 10010 10011 10100 10101 10110 10111 11000 11001 11010 11011 11100 11101 11110 11111 </code></pre> <p>To be honest there are a plethora of ways this can be done, this is just one. I purposely modeled it after your original implementation so as to limit algorithm change. I hope it helps you understand the problem and one way around it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload