C ++中的笛卡尔积 [英] Cartesian Product in c++

查看:303
本文介绍了C ++中的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找如何提出可以应用笛卡尔积的代码段。假设我有两个数组:

I have been searching for weeks on how to come up with piece of code which I could applied the cartesian product. Let's say I have two arrays :

int M[2]= {1,2};
int J[3] = {0,1,2};

所以代码将采用规则MXJ
的两个数组对(1,0)(1,1)(1,2)(2,0)(2,1)(2,2)和我希望将新结果保存到新数组中,其中的每个索引数组包含一对,例如c [0] =(1,0)。
请提供帮助:(

So the code will takes those two arrays in apply the rule M X J therefore we will have the pairs (1,0)(1,1)(1,2)(2,0)(2,1)(2,2) and I want the new result to be saved into a new array where each index in the array contains a pair , for example c[0] = (1,0). Help please :(

推荐答案

下面是使用向量实现笛卡尔积的简单示例。向量是更好的选择

Here is an simple example of implementing Cartesian product using vector. Vectors are much better choice as we do not need to worry about its size as it dynamically changes it.

#include <iostream>
#include <vector>
#include <utility>
using namespace std;

int main() {
    int M[2]= {1,2};
    int J[3] = {0,1,2};
    vector<pair<int,int>> C;

    for (int i = 0; i < sizeof(M)/sizeof(M[0]); i++)
    {
        for (int j = 0; j < sizeof(J)/sizeof(J[1]); j++)
        {
            C.push_back(make_pair(M[i],J[j]));
        }  
    }

    /*
    for (vector<int>::iterator it = C.begin(); it != C.end(); it++)
    {
        cout << *it << endl;
    }

    */

    for (int i = 0; i < C.size(); i++)
    {
        cout << C[i].first << "," << C[i].second << endl;
    }
}

这是链接,其中我实现了上述代码。尽管我不会发布与您的问题直接相关的解决方案,但评论中发布的链接已经包含答案,这就是我发布原因的原因。

Here is the link where I implemented the above code. Although I wouldn't post solution directly relating to your question, links posted in the comments already contains answer which is why I posted.

这篇关于C ++中的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆