Search code examples
c++stringvectortemporarycartesian-product

Generate the Cartesian Product of 2 vector<string>s In-Place?


If I want to get the Cartesian Product of these two vector<string>s:

vector<string> final{"a","b","c"};
vector<string> temp{"1","2"};

But I want to put the result in final, such that final would contain:

a1
a2
b1
b2
c1
c2

I'd like to do this without creating a temporary array. Is it possible to do this? If it matters, the order of final is not important.


Solution

  • You may try the following approach

    #include <iostream>
    #include <vector>
    #include <string>
    
    int main() 
    {
        std::vector<std::string> final{ "a", "b", "c" };
        std::vector<std::string> temp{ "1", "2" };
    
        auto n = final.size();
    
        final.resize( final.size() * temp.size() );
    
        for ( auto i = n, j = final.size(); i != 0; --i )
        {
    
            for ( auto it = temp.rbegin(); it != temp.rend(); ++it )
            {
                final[--j] = final[i-1] + *it; 
            }
    
        }
    
        for ( const auto &s : final ) std::cout << s << ' ';
        std::cout << std::endl;
    
        return 0;
    }
    

    The program output is

    a1 a2 b1 b2 c1 c2