[Solved] Create 2^n variables with a pattern


If you like to create a piece of code having that many different variables with a different name, I suggest you start writing your own code generator. The code below should be a good start.

#include <sstream>
#include <iostream>
#include <string>
#include <vector>

namespace {
template <typename Function>
void bitExecutor(int nrOfBits, std::vector<bool> &bits, const Function &f) {
  if (nrOfBits) {
    bits.push_back(false);
    bitExecutor(nrOfBits - 1, bits, f);
    bits.back() = true;
    bitExecutor(nrOfBits - 1, bits, f);
    bits.pop_back();
  } else {
    f(bits);
  }
}
}

int main(int argc, char **argv) {
  int nrOfBits = 4; // Let's assume runtime init

  std::vector<std::string> values;
  std::vector<bool> bits;
  bitExecutor(nrOfBits, bits, [&values](std::vector<bool> &bits) {
    std::string buffer;
    buffer += "n";
    for (auto &&bit : bits) {
      if (bit)
        buffer += "1";
      else
        buffer += "0";
    }
    values.emplace_back(std::move(buffer));
  });

  for (const auto &value : values)
    std::cout << value << std::endl;
  return 0;
}

That said, I think you are trying to tackle the wrong problem here. Why would like to have a lot variables representing the same thing, while you can use things like std::vector, which totally works with indexing. See also the ‘values’ variable in this example, which you can index like values[0] // first element … and get the matching values

solved Create 2^n variables with a pattern