gpt4 book ai didi

c++ - 用C++ 17的功能方式做笛卡尔积

转载 作者:行者123 更新时间:2023-12-02 09:57:43 24 4
gpt4 key购买 nike

我正在尝试使用闭包/自定义函数来实现笛卡尔乘积,闭包是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)
}
首先,使用第一个 vector 的每个元素,迭代第二个 vector ,然后将应用函数的结果存储在结果 vector 中。
该代码仅用于表示目的。它不会编译。除其他外,它给出 'b' is not captured in {vector<int>::iterator p = b.begin();错误。
如何纠正此代码和/或如何正确地使用闭包实现笛卡尔运算?

最佳答案

您的编译问题是因为您没有在lambda中捕获所需的变量,并且缺少一些;
但是,执行笛卡尔乘积的一种更简单的方法是使用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开始,添加了范围和 View ,因此您可以变得更具创意:
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循环可能是笛卡尔乘积的最佳方法,但是这应该使您体会到令人兴奋的可能性。
这是 demo

关于c++ - 用C++ 17的功能方式做笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64405625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com