title: Bit Masking to select Vector/Set Elements?
body: <h2>Objective</h2>
  
  <p>I'm trying to extract elements withing a container (e.g. vector, set, etc...) but instead of using the index, I am using the bit masking technique.</p>
  
  <h2>Scenario:</h2>
  
  <pre><code>vector&lt;string&gt; alphabets {"a", "b", "c", "d", "e"};
  </code></pre>
  
  <h2>Test Case:</h2>
  
  <ol>
  <li><p>Input: <code>5</code> (eqivalent bitmask: <code>00101</code>) </p>
  
  <p>Output: new vector <code>{"c", "e"}</code></p></li>
  <li><p>Input <code>13</code> (bitmask: <code>01101</code>)</p>
  
  <p>Output vector: <code>{"b", "c", "e"}</code></p></li>
  </ol>
  
  <h2>Naive Working Solution:</h2>
  
  <pre><code>vector&lt;string*&gt; extract(int mask){
      vector&lt;string*&gt; result;
      bitset&lt;n&gt; bits(mask);
      for (int j = 0; j &lt; n; ++j) {
          if (bits[j]){
              result.push_back(&amp;alphabets[j]);
          }
      }
  }
  </code></pre>
  
  <h2>Further Improvement</h2>
  
  <ul>
  <li>time complexity</li>
  <li>space complexity</li>
  <li>concept/idea??</li>
  <li>API availability??</li>
  </ul>
  
  <h1>Example Use case.</h1>
  
  <p>Permutate all combination of a,b,c,d,e, whereby the a,b,c,d,e is wrapped on a container. (other approached has been mentioned in the <a href="https://stackoverflow.com/questions/9430568/generating-combinations-in-c">Generating combinations in c++</a> question.)</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;iostream&gt;
  #include &lt;algorithm&gt;
  #include &lt;string&gt;
  #include &lt;bitset&gt;
  
  using namespace std;
  
  
  int main(){
      const int n = 5;
  
      vector&lt;string&gt; alphabets {"a", "b", "c", "d", "e"};
  
      for ( int i = 0; i &lt; pow(2, n); ++i){
          vector&lt;string*&gt; result;
          bitset&lt;n&gt; bits(i);
          for (int j = 0; j &lt; n; ++j) {
              if (bits[j]){
                  result.push_back(&amp;alphabets[j]);
              }
          }
  
          for (auto r: result){
              cout &lt;&lt; *r;
          }
          cout &lt;&lt; endl;
      }
      return 0;
  }
  </code></pre>