对于任何给定的 n
,我需要创建一个长度为 n
的 vector vector 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;
}
}
关于c++ - -1、+1 的所有组合的 vector 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39078685/