问题描述
在下面的代码中,我想获取长度为 n 的所有乘积,这是一个给函数的参数。显然,该乘积函数不适用于长度参数。当我给出一个整数时,代码不会抱怨。 我还想遍历产品中的所有元素并打印它们,但它说它不能打印元组。
我该如何解决这个问题?
#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;
}
}
使用参数 n 时出现的错误:
no instance of overloaded function "iter::product" matches the argument list,argument types are: (std::vector<int,std::allocator<int>>)
在使用 2 作为参数时尝试打印组合时遇到的错误:
this range-based 'for' statement requires a suitable "begin" function and none was found
解决方法
iter::product<n>
要求 n
是编译时常量,但它不是。
这个库有一个关于实现一个需要运行时重复次数的版本的公开问题。
元组不是可以用 for
循环的东西。运行时计数 product
的返回值不能是元组,因此不要担心原始案例的第二个错误。
你也必须用编译时常量索引一个元组。
for (auto&& combination : iter::product<2>(options)) {
std::cout << get<0>(combination) << " " << get<1>(combination) << " " << std::endl;
}
如果您对计数进行模板化,则可以使用 std::index_sequence
来保存数字的编译时间序列
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>{});
}
}