Search code examples
binaryfiles

How to get all possible binary numbers in a vector


I'm looking for a way to generate all possible binary combinations and insert that into a vector of strings.

For example, if I have n=3, I would like to create a string of vectors that contains all the possible combinations from ["000", ..., "111"].

I have created a code that can generate binary strings of the values.

std::vector<std::string> get_combs(std::vector<std::string> vector, const int Z){
  

  //I'm not sure why this line causes the error
  constexpr size_t N = Z;
 

  for(size_t i=0; i<(1<<N); ++i) {
    std::bitset<N> bs = i;
    vec.push_back(bs.to_string());
  }
  
  return vec;
}
  
// Driver Code 
int main() 
{ 
    int Z = 2; 
    std::vector<std::string> values;
    values = get_combs(values, const int Z);
}

But right now it's just printing as 0 0 0 1 1 0 1 1


Solution

  • Is N known at compile-time? If so std::bitset<N> could be useful:

    #include <iostream>
    #include <bitset>
    #include <vector>
    
    using namespace std;
    
    int main() 
    {
        constexpr size_t N = 3;
    
        std::vector<std::string> vec;
        for (size_t i=0; i<(1<<N); ++i) {
            std::bitset<N> bs = i;
            vec.push_back(bs.to_string());
        }
    
        // Prints "000 001 010 011 100 101 110 111"
        for (auto& elem: vec) cout << elem << ' ';
        cout << endl;
    
        return 0;
    }
    

    https://godbolt.org/z/WxWz43