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

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

本文关键字:lt string gt 笛卡尔积 向量      更新时间:2023-10-16

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

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

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

a1
a2
b1
b2
c1
c2

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

您可以尝试以下方法

#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 

尝试函数cartesian:

#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("%sn", s.c_str());
 }
}

这对我有效:

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

这只是莫斯科解决方案中瓦尔的个人偏好选项。我认为动态数组可能更快,因为分支更少。但我还没来得及写一个计时测试台。

给定输入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