Generate the Cartesian Product of 2 vectors In-Place?

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

    You may try the following approach

    #include 
    #include 
    #include 
    
    int main() 
    {
        std::vector final{ "a", "b", "c" };
        std::vector 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 
    

提交回复
热议问题