Can UnaryOperator be a member function when std::transform is called

后端 未结 3 998
终归单人心
终归单人心 2021-01-22 21:07

Based on std::transform

template < class InputIterator, class OutputIterator, class UnaryOperator >
  OutputIterator transform ( InputIterator first1, Inpu         


        
相关标签:
3条回答
  • 2021-01-22 21:52

    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());
    
    0 讨论(0)
  • 2021-01-22 21:58

    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)
    );
    
    0 讨论(0)
  • 2021-01-22 21:58

    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(); });
      }
    };
    
    0 讨论(0)
提交回复
热议问题