C++ 如何使用长度参数的iter::product
在下面的代码中,我想得到长度为n的所有乘积,这是函数的一个参数。显然,此产品功能不适用于长度参数。当我给出一个整数时,代码不会抱怨。 我还想迭代产品中的所有元素并打印它们,但它说它不能打印元组 我怎样才能解决这个问题C++ 如何使用长度参数的iter::product,c++,itertools,cartesian-product,C++,Itertools,Cartesian Product,在下面的代码中,我想得到长度为n的所有乘积,这是函数的一个参数。显然,此产品功能不适用于长度参数。当我给出一个整数时,代码不会抱怨。 我还想迭代产品中的所有元素并打印它们,但它说它不能打印元组 我怎样才能解决这个问题 #include <../cppitertools-master/product.hpp> vector<complex<double>> print_products(int n) { vector<complex<dou
#include <../cppitertools-master/product.hpp>
vector<complex<double>> print_products(int n) {
vector<complex<double>> solutions = {};
vector<int> options = { 1, -1 };
for (auto&& combination : iter::product<n>(options)) {
for (auto&& c : combination) {
cout << c << " ";
}
cout << endl;
}
}
iter::product
要求n
是编译时常量,但事实并非如此
这个库有一个未解决的问题,就是如何实现一个执行运行时重复计数的版本
元组不是可以循环使用的对象。运行时计数product
的返回值不能是元组,因此不要担心原始案例的第二个错误
您还必须使用编译时常量索引元组
for (auto&& combination : iter::product<2>(options)) {
std::cout << get<0>(combination) << " " << get<1>(combination) << " " << std::endl;
}
您应该链接到已使用的库<代码>组合
应该与std::tuple
等效,因此直接的std::cout
不起作用。它应该类似于std::apply([](auto…args){((std::coutiter::product
不能与运行时值n
,template void print_products();
似乎更合适。(C++17)可能用于避免std::index_sequence
用法:std::apply([](auto&…args){(std::cout.)
this range-based 'for' statement requires a suitable "begin" function and none was found
for (auto&& combination : iter::product<2>(options)) {
std::cout << get<0>(combination) << " " << get<1>(combination) << " " << std::endl;
}
template <typename T, size_t... Is>
void print_product(T&& combination, std::index_sequence<Is...>) {
(std::cout << get<Is>(std::forward<T>(combination))), ...) << std::endl;
}
template <size_t N>
void print_products() {
vector<int> options = { 1, -1 };
for (auto&& combination : iter::product<N>(options)) {
print_product(combination, std::make_index_sequence<N>{});
}
}