gpt4 book ai didi

C++ boost 或 STL `y += f(x)` 类型算法

转载 作者:太空狗 更新时间:2023-10-29 23:38:02 25 4
gpt4 key购买 nike

我知道我可以通过使用带有两个输入迭代器的变换来执行 y[i] += f(x[i])。然而它似乎有点违反直觉并且比 for 循环更复杂。

使用 boost 或 STL 中的现有算法是否有更自然的方法来做到这一点?我找不到干净的等价物。

这里是转换 (y = y + a*x):

using boost::lambda;
transform(y.begin(), y.end(), x.begin(), y.begin(), (_1 + scale*_2);
// I thought something may exist:
transform2(x.begin(), x.end(), y.begin(), (_2 + scale*_1);
// it does not, so no biggie. I will write wrapper

谢谢

最佳答案

有几种方法可以做到这一点。

正如您所指出的,您可以将 transform 与许多谓词一起使用,其中一些或多或少是自动生成的:

std::vector<X> x = /**/;
std::vector<Y> y = /**/;

assert(x.size() == y.size());

//
// STL-way
//
struct Predicate: std::binary_function<X,Y,Y>
{
Y operator()(X lhs, Y rhs) const { return rhs + f(lhs); }
};

std::transform(x.begin(), x.end(), y.begin(), y.begin(), Predicate());

//
// C++0x way
//
std::transform(x.begin(), x.end(), y.begin(), y.begin(),
[](X lhs, Y rhs) { return rhs += f(lhs); });

现在,如果我们有一个包含索引范围的vector,我们可以用更“pythony”的方式来实现:

std::vector<size_t> indices = /**/;


//
// STL-way
//
class Predicate: public std::unary_function<size_t, void>
{
public:
Predicate(const std::vector<X>& x, std::vector<Y>& y): mX(x), mY(y) {}
void operator()(size_t i) const { y.at(i) += f(x.at(i)); }
private:
const std::vector<X>& mX;
std::vector<Y>& mY;
};

std::foreach(indices.begin(), indices.end(), Predicate(x,y));

//
// C++0x way
//
std::foreach(indices.begin(), indices.end(), [&](size_t i) { y.at(i) += f(x.at(i)); });

//
// Boost way
//
BOOST_FOREACH(size_t i, indices) y.at(i) += f(x.at(i));

我不知道是否与 View 有关,它们通常允许一些漂亮的语法。当然这里我觉得有点难,因为自修改y

关于C++ boost 或 STL `y += f(x)` 类型算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2745146/

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