本文介绍了多个字符串的C ++笛卡尔乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串存储在向量中: vector< string> ex = {ab,cd,ef}
现在我需要创建这些字符串的笛卡儿乘积(向量中的字符串数,字符串的长度也是固定的!)。结果应为:

I have strings stored in a vector as such: vector<string> ex = {"ab", "cd", "ef"}.Now I need to create the cartesian product of these strings (number of strings in the vector, nor the length of the strings is fixed!). The result should be:

  ace
  acf
  ade
  adf
  bce
  bcf
  bde
  bdf

字符串的单个字母应该用于笛卡尔乘积而不是整个string!

The single letters of the strings should be used for the cartesian product not the entire string!

推荐答案

Ok我想出了一个解决方案。它可能不是最好的,也有一些改进的代码可能,但它足够我的目的,如果有人需要它:

Ok I came up with a solution. It might not be the best one and there are for sure some improvements of the code possible but its enough for my purposes and in case someone needs it too:

vector<string> getProducts(vector<string> s) {
int combinations = 1;
vector<string> res;
for (unsigned int i=0; i<s.size(); i++) {
    combinations *= s.at(i).length();
}

for (unsigned int i=0; i<s.size(); i++) {
    string cur = s.at(i);
    int div = combinations / cur.length();
    int count = 0;
    for (unsigned int ch=0; ch<cur.length(); ch++) {
        for (int len=0; len<div; len++) {
            if (i==0) {
                res.push_back(string(cur.substr(ch, 1)));
            } else {
                string tmp = res.at(count);
                tmp.append(string(cur.substr(ch,1)));
                res.at(count) = tmp;
            }
            count++;
        }


        if ((ch == cur.length()-1) && (count <= res.size()-1) && i>0) {
            ch = -1;
        }
    }
    combinations = div;
}

return res;

}

这篇关于多个字符串的C ++笛卡尔乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 16:55