Any*_*orn 2 c++ algorithm boost
我知道我可以y[i] += f(x[i])
使用两个输入迭代器进行转换.然而,它似乎有点违反直觉,比循环更复杂.
有没有更自然的方法来使用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
Run Code Online (Sandbox Code Playgroud)
谢谢
有几种方法可以做到这一点.
如您所述,您可以使用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); });
Run Code Online (Sandbox Code Playgroud)
现在,如果我们有一个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));
Run Code Online (Sandbox Code Playgroud)
我不知道是否可能与视图有关,它们通常允许一些漂亮的语法.当然,由于自我修改,我认为这有点困难y
.