如何获取向量中所有可能的二进制数

How to get all possible binary numbers in a vector

我正在寻找一种方法来生成所有可能的二进制组合并将其插入到字符串向量中。

例如,如果我有 n=3,我想创建一个包含 ["000", ..., "111"].

我创建了一个可以生成值的二进制字符串的代码。

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);
}

但现在它只是打印为 0 0 0 1 1 0 1 1

N 在编译时已知吗?如果是这样 std::bitset<N> 可能会有用:

#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

非递归转换版本(遍历所有数字并将它们转换为二进制数字字符串):

std::string to_binstring(int x, int width)
{
    std::string s(width, '0');
    for (int i = 0; i < width; i++)
    {
        s[i] = '0' + x % 2;
        x /= 2;
    }
    std::reverse(s.begin(), s.end());
    return s;
}

std::vector<std::string> all_binstrings(int width)
{
    const unsigned int limit = 1 << width;
    std::vector<std::string> bins;
    for (unsigned int i = 0; i < limit; i++)
    {
        bins.push_back(to_binstring(i, width));
    }
    return bins;
}

递归字符串构建版本(将“0”和“1”附加到所有较短的字符串):

std::vector<std::string> recursive_binstrings(int width)
{
    if (width == 1)
    {
        return {"0", "1"};
    }
    std::vector<std::string> rest = recursive_binstrings(width-1);
    std::vector<std::string> appended;
    for (const auto& s: rest)
    {
        appended.push_back(s + '0');
        appended.push_back(s + '1');
    }
    return appended;
}