How do I create a vector of bitmasks that basically replaces a vector of boolean in C++11?

Viewed 120

I am trying to create a vector of bitmasks to store true/ false values which are going to tell me if the value particular index in another vector needs to be printed or not.

eg: std::vector<int> a ; b is a vector of bitmasks which is going to hold flag values that correspond to the integer vector a and this flag tells me if that particular value at the corresponding index needs to be printed or not.

a {1,2,3}  
b { true, false ,true} // I need a similar bitmask which would help me print 1 and 3 

this task can be achieved in other ways the problem I am working in requires the use of bitmask. Thanks in advance for helping me with this.

1 Answers

As many suggested already, I would have done this like this:

  • myBitset will keep the flags. 1(set) for print flag and 0(clear) for non-print flag
#include <bitset>
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char** argv){

  std::vector<int> a {1,2,3,4,5,6,7,8,9,10};

  std::bitset<10> myBitset;

  myBitset.set(3);             // set fourth bit  ==> display 4
  myBitset.set(6);             // set seventh bit ==> display 7
  myBitset[8] = true;          // set nineth bit ==> display 9
  myBitset[9] = myBitset[3];   // set 10th bit ==> display 10

  std::cout << "Mybitset" << myBitset << endl;

  for (int i=0; i<a.size(); i++)
  {
      if (myBitset.test(i))
      {
          std::cout << a.at(i);
      }
  }

  return (0);
}

The ouput would be:

1101001000
47910
Related