码迷,mamicode.com
首页 > 其他好文 > 详细

Generate ordered cartesian product of sequences

时间:2015-03-03 20:46:02      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:笛卡尔积   cartesian product   c++   

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

标签:笛卡尔积   cartesian product   c++   

原文地址:http://blog.csdn.net/cqdjyy01234/article/details/44041925

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!