Based on std::transform
template < class InputIterator, class OutputIterator, class UnaryOperator >
OutputIterator transform ( InputIterator first1, Inpu
You need a helper object, like std::less but for a unary operator.
C++11 lambdas make this incredibly easy:
std::transform(xs.begin(), xs.end(), ys.begin(), [](the_type x){ return -x; });
std::transform(xs.begin(), xs.end(), ys.begin(), [](the_type x){ return !x; });
std::transform(xs.begin(), xs.end(), ys.begin(), [](the_type x){ return ~x; });
Or, use these flexible helpers:
struct negate
{
template<typename T>
auto operator()(const T& x) const -> decltype(-x) { return -x; }
};
struct invert
{
template<typename T>
auto operator()(const T& x) const -> decltype(!x) { return !x; }
};
struct complement
{
template<typename T>
auto operator()(const T& x) const -> decltype(~x) { return ~x; }
};
std::transform(xs.begin(), xs.end(), ys.begin(), negate());
std::transform(xs.begin(), xs.end(), ys.begin(), invert());
std::transform(xs.begin(), xs.end(), ys.begin(), complement());
No (well, not directly). You need to use an adaptor, either old std::mem_fun
(together with bind1st
, IIRC) or std::bind
/boost::bind
.
std::transform(
xs.begin(), xs.end(), ys.begin(),
std::bind(&Class::member, &class_instance)
);
It is pretty easy to do if you wrap the call in lambda:
#include <algorithm>
#include <vector>
class C {
public:
int op() const { return 1; }
};
class D {
int op() { return 1; }
void f() {
std::vector<C> xs;
std::vector<int> ys;
std::transform(xs.begin(), xs.end(), ys.begin(),
[](const C& x) { return x.op(); });
std::transform(xs.begin(), xs.end(), ys.begin(),
[this](const C& x) { return this->op(); });
}
};