Generate the Cartesian Product of 2 vectors In-Place?

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

    This is just a personal preference option to Vald from Moscow's solution. I think it may be faster for dynamic arrays because there would be less branching. But I haven't gotten around to writing a timing test bench.

    Given the inputs vector final and vector temp:

    const auto size = testValues1.first.size();
    
    testValues1.first.resize(size * testValues1.second.size());
    
    for (int i = testValues1.first.size() - 1; i >= 0; --i){
        testValues1.first[i] = testValues1.first[i % size] + testValues1.second[i / size];
    }
    

    EDIT:

    Nope, this solution is slower not faster: http://ideone.com/e.js/kVIttT

    And usually significantly faster, though I don't know why...

    In any case, prefer Vlad from Moscow's answer

提交回复
热议问题