首页 > 其他 > 详细

Generate ordered cartesian product of sequences

时间:2015-03-03 20:42:52      阅读:281      评论:0      收藏:0      [点我收藏+]

问题来源: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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!