Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65853673/how-do-i-create-a-vector-of-bitmasks-that-basically-replaces-a-vector-of-boolean

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...