Generate the Cartesian Product of 2 vectors In-Place?

前端 未结 4 573
后悔当初
后悔当初 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:01

    Try the function cartesian:

    #include 
    #include 
    
    using namespace std;
    
    void cartesian(vector& f, vector &o) {
    int oldfsize = f.size();
    f.resize(oldfsize * o.size());
    for (int i = o.size() - 1; i>=0; i--) {
      for (int j = 0; j < oldfsize; j++) {
         f[i*oldfsize + j] = f[j] + o[i];
      }
     }
    }
    
    
    int main() 
    {
    vector f{"a","b","c"};
    vector temp{"1","2"};
    cartesian(f, temp);
    for (auto &s: f) {
      printf("%s\n", s.c_str());
     }
    }
    

提交回复
热议问题