gpt4 book ai didi

c++ - -1、+1 的所有组合的 vector 的 vector

转载 作者:行者123 更新时间:2023-11-28 05:32:40 27 4
gpt4 key购买 nike

对于任何给定的 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;
}
}

Test Example

关于c++ - -1、+1 的所有组合的 vector 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39078685/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com