所有-1和+1组合的向量的向量

vector of vectors of all combinations of -1, +1

本文关键字:向量 组合 所有      更新时间:2023-10-16

对于任何给定的n,我需要创建一个长度为n std::vector<std::vector<int>>的向量的向量,包含 -1+1的所有可能组合。例如,对于n=3,我需要

std::vector<std::vector<int>> v = {
  { 1,  1,  1},
  { 1,  1, -1},
  { 1, -1,  1},
  { 1, -1, -1},
  {-1,  1,  1},
  {-1,  1, -1},
  {-1, -1,  1},
  {-1, -1, -1}
};

提示吗?

使用二进制表示的简单解决方案,并测试位值。我使用了std::bitset,尽管你也可以使用简单的c风格位操作。

#include <bitset>
int main(){
    int n=3;
    int to = pow(2,n);
    std::vector<std::vector<int>> result;
    for (int i=0; i < to; i++){
        std::bitset<32> b(i);
        std::vector<int> vec1;
        for (int j=0; j < n; j++){
            int value = b.test(j) ? 1 : -1;
            vec1.push_back(value);
        }
        result.push_back(vec1);
    }
    // Printing out result
    for (auto& vec : result){
        for (auto val : vec){
            cout << val;
        }
        cout << endl;
    }
}
测试示例

对于较大的(n)值,您可能希望提高效率:

std::vector<std::vector<int>> v;
v.reserve(1 << n);
for (unsigned int i = 0; i < (1 << n); i++)
{
    std::vector<int> vi (n, 0);
    for (unsigned int j = 0; j < n; j++)
        vi[n - 1 - j] = (i & (1 << j)) ? (-1) : (+1);
    v.push_back(vi);
}

我相信有人能想出一个模板元程序,可以在编译时为常数(n)构造(v)

按照@sascha的建议,这里有一个方法,将+-1附加到给定的列表集。

#include <vector>
#include <iostream>
std::vector<std::vector<int>>
append_plus_minus(const std::vector<std::vector<int>> & in)
{
  auto out = in;
  out.insert(out.end(), in.begin(), in.end());
  for (std::size_t i=0; i < in.size(); i++) {
    out[i].push_back(+1);
    out[i+in.size()].push_back(-1);
  }
  return out;
}
int main() {
  const int n = 5;
  std::vector<std::vector<int>> b_combinations = {{}};
  for (std::size_t i=0; i < n; i++) {
    b_combinations = append_plus_minus(b_combinations);
  }
  for (std::size_t i=0; i < b_combinations.size(); i++) {
     for (std::size_t j=0; j < b_combinations[i].size(); j++) {
       std::cout << b_combinations[i][j] << " ";
     }
     std::cout << std::endl;
  }
  return 0;
}