问题来源:http://stackoverflow.com/questions/25391423/ordered-cartesian-product-of-arrays
2个序列时的情形已解决http://stackoverflow.com/questions/4299458/efficient-sorted-cartesian-product-of-2-sorted-array-of-integers,本文将其扩展到一般情形。
测试代码
#include <cartesian.h>
#include <iostream>
#include <functional>
#include <random>
int main() {
using type = int;
std::vector<type> a = { 10, 9, 2, 1, 1 }, b, c;
{
for (a1 : a) for (a2 : a) for (a3 : a) for (a4 : a) b.push_back(a1*a2*a3*a4);
std::sort(b.begin(), b.end(), std::greater<type>());
}
{
auto it1 = make_cartesian_product(a.begin(), a.end(), a.begin(), a.end(), std::multiplies<type>(), std::less<type>());
auto it2 = make_cartesian_product(std::move(it1.first), std::move(it1.second), a.begin(), a.end(), std::multiplies<type>(), std::less<type>());
auto it = make_cartesian_product(std::move(it2.first), std::move(it2.second), a.begin(), a.end(), std::multiplies<type>(), std::less<type>());
while (it.first != it.second) {
c.push_back(*it.first);
++it.first;
}
}
std::cout << "equal? " << (b == c) << "\n";
for (val : c) std::cout << val << " ";
std::cout << "\n";
return 0;
}运行结果
Generate ordered cartesian product of sequences
原文地址:http://blog.csdn.net/cqdjyy01234/article/details/44041925