Cartesian Product in c++

后端 未结 4 778
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 02:16

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]= {         


        
4条回答
  •  醉梦人生
    2020-12-15 02:43

    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 
    #include 
    #include 
    using namespace std;
    
    int main() {
        int M[2]= {1,2};
        int J[3] = {0,1,2};
        vector> 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::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.

提交回复
热议问题