就地生成 2 个向量<string>s 的笛卡尔积?

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

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

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

但我想将结果放在 final 中,这样最终将包含:

a1
a2
b1
b2
c1
c2

我想在不创建临时数组的情况下执行此操作。是否有可能做到这一点?如果重要,final 的顺序并不重要。

试试笛卡尔函数:

#include <vector>
#include <string>

using namespace std;

void cartesian(vector<string>& f, vector<string> &o) {
int oldfsize = f.size();
f.resize(oldfsize * o.size());
for (int i = o.size() - 1; i>=0; i--) {
  for (int j = 0; j < oldfsize; j++) {
     f[i*oldfsize + j] = f[j] + o[i];
  }
 }
}


int main() 
{
vector<string> f{"a","b","c"};
vector<string> temp{"1","2"};
cartesian(f, temp);
for (auto &s: f) {
  printf("%s\n", s.c_str());
 }
}

您可以尝试以下方法

#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 

这对我有用:

void testCartesianString(vector<string>& final,
                         vector<string>const& temp)
{
   size_t size1 = final.size();
   size_t size2 = temp.size();

   // Step 1.
   // Transform final to : {"a","a","b","b","c","c"}
   final.resize(size1*size2);
   for ( size_t i = size1; i > 0; --i )
   {
      for ( size_t j = (i-1)*size2; j < i*size2; ++j )
      {
         final[j] = final[i-1];
      }
   }

   // Step 2.
   // Now fix the values and
   // change final to : {"a1","a2","b1","b2","c1","c2"}
   for ( size_t i = 0; i < size1; ++i )
   {
      for ( size_t j = 0; j < size2; ++j )
      {
         final[i*size2+j] = final[i*size2+j] + temp[j];
         cout << final[i*size2+j] << " ";
      }
      cout << endl;
   }
}

这只是 Vald from Moscow 解决方案的个人偏好选项。我认为动态数组可能会更快,因为分支会更少。但是我还没有抽出时间写一个时序测试平台。

给定输入 vector<string> finalvector<string> 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];
}

编辑:

不,这个解决方案不是更快而是更慢:http://ideone.com/e.js/kVIttT

而且通常明显更快,虽然我不知道为什么...

无论如何,更喜欢Vlad from Moscow的回答