所有-1和+1组合的向量的向量
vector of vectors of all combinations of -1, +1
对于任何给定的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;
}
相关文章:
- 检查向量是否具有所有可能的字符组合
- 从向量的向量中删除向量的组合
- 如何得到几个子向量的组合
- 如何组合两个整数向量
- 如果我们从每个 Y 向量中选择一个值,则 X 数字的每个组合都可能
- 在不使用递归的情况下求解所有 2D 字符串向量组合?(C++)
- 字符串向量的有效组合
- 向量的高效组合最小值和平均值计算
- 如何在 Boost.Sprit.Qi 中从向量制作组合的 ascii::string 规则<string>?
- 将多个向量(函数结果)组合到一个使用模板中
- 双重释放或损坏(输出):使用向量的组合算法0x0000000001a880a0***
- 如何沿行组合两个向量?
- 创建多个向量的所有可能组合
- 如何在 c++ 中将集合和数组合并到向量中
- 在C++编程语言中,如何用n个向量长度的所有可能的字符串组合来填充向量
- 在 C++11 中计算字母和单词的双字母组合的 std::线程向量的问题
- 是否可以将GSL向量组合成单个向量
- 打印所有子向量组合 + 问题
- 确定某个hamming权的二进制向量的所有子向量组合
- c++将向量中的向量组合成一个向量