Generate the Cartesian Product of 2 vectors In-Place?

前端 未结 4 565
后悔当初
后悔当初 2021-01-25 08:21

If I want to get the Cartesian Product of these two vectors:

vector final{\"a\",\"b\",\"c\"};
vector temp{         


        
4条回答
  •  有刺的猬
    2021-01-25 09:22

    This works for me:

    void testCartesianString(vector& final,
                             vectorconst& temp)
    {
       size_t size1 = final.size();
       size_t size2 = temp.size();
    
       // Step 1.
       // Transform final to : {"a","a","b","b","c","c"}
       final.resize(size1*size2);
       for ( size_t i = size1; i > 0; --i )
       {
          for ( size_t j = (i-1)*size2; j < i*size2; ++j )
          {
             final[j] = final[i-1];
          }
       }
    
       // Step 2.
       // Now fix the values and
       // change final to : {"a1","a2","b1","b2","c1","c2"}
       for ( size_t i = 0; i < size1; ++i )
       {
          for ( size_t j = 0; j < size2; ++j )
          {
             final[i*size2+j] = final[i*size2+j] + temp[j];
             cout << final[i*size2+j] << " ";
          }
          cout << endl;
       }
    }
    

提交回复
热议问题