繁体   English   中英

在 C++17 中以函数方式做笛卡尔积

[英]Doing cartesian product the functional way in C++17

我正在尝试使用闭包/自定义函数实现笛卡尔积,闭包是function(x,y) = pow(x,2) + pow(y,2)并以函数方式实现它,即不使用 C-样式循环。

这是我的看法。

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
void print (vector<int> aux) {
  vector<int>::iterator it = aux.begin();
  while(it != aux.end()){
    cout << *it << " ";
    it++; }}

int main() {
  vector<int> a{1,2};
  vector<int> b{3,4};
  vector<int> cartesian(4);
  transform (a.begin(), a.end(), b.begin(), cartesian.begin(), [](int &i)
         {vector<int>::iterator p = b.begin();
           for_each(begin(b), end(b), [](int &n) { return pow(i,2) + pow(n,2) })});
  print(cartesian);
  // desired output is: 10,17,13,20 (cartesian operation)
}

首先,使用第一个向量的每个元素,迭代第二个向量,然后将应用函数的结果存储在结果向量中。

该代码用于表示目的。 它不编译。 它给出了'b' is not captured in {vector<int>::iterator p = b.begin(); 错误等。

如何纠正此代码和/或如何使用闭包正确实现笛卡尔运算?

您的编译问题是因为您没有在 lambdas 中捕获所需的变量,并且您缺少一些; .

但是,一个更简单的笛卡尔积的方法是使用 2 个嵌套循环,如下所示:

for (int i : a)
  for (int j : b)
    cartesian.push_back(i * i + j * j);

如果你想使用算法,那么你可以写:

for_each(begin(a), end(a), [&](int i) { 
  for_each(begin(b), end(b), [&](int j) { 
    cartesian.push_back(i * i + j * j); 
  });
});

虽然我发现这更难阅读,并且并没有太大帮助,因为for_each是一种算法,它恰好具有内置语言结构,类似于transform


从 c++20 开始,添加了范围和视图,因此您可以获得更多创意:

namespace rs = std::ranges;
namespace rv = std::views;

auto product = [=](int i) 
{
   auto  op = [=](int j) { return i * i + j * j;};

   return b | rv::transform(op);
};
  
rs::copy(a | rv::transform(product) 
           | rv::join,
         std::back_inserter(cartesian));

同样,原始的嵌套for循环可能是笛卡尔积的最佳方法,但这应该会让您体验令人兴奋的可能性。

这是一个演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM