生成2个向量string的就地笛卡尔积? [英] Generate the Cartesian Product of 2 vector<string>s In-Place?

查看:64
本文介绍了生成2个向量string的就地笛卡尔积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想获得这两个 vector< string> s的笛卡尔积:

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"};

但是我想将结果放入 final 中,以便final包含:

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

a1
a2
b1
b2
c1
c2

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.

推荐答案

您可以尝试以下方法

#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;
}

程序输出为

a1 a2 b1 b2 c1 c2 

这篇关于生成2个向量string的就地笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆