如何链接C ++`transform`和`inner_product`调用?

时间:2017-04-10 21:23:37

标签: c++

我想做点什么:

begin()

换句话说,只需隐式使用end()first作为lastclass UserSerializer < ActiveModel::Serializer include ApplicationHelper attributes :id, :formatted def formatted format_name(object) end end 迭代器并将结果链接起来。

是否有任何东西(例如某些图书馆)允许这样做?

2 个答案:

答案 0 :(得分:0)

只需编写自己的类来增强std::vector

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
#include <utility>

template < typename T >
class augmented_vector
{
  std::vector < T > m_vec;
public:
  augmented_vector() : m_vec() {}
  explicit augmented_vector(std::vector<T> const& in) : m_vec(in) {}

  void push_back ( T&& value )
  {
    m_vec.push_back(std::forward<T>(value));
  }

  template < typename F >
  augmented_vector < T > transform(F const& f)
  {
    std::vector < T > new_vec(m_vec.size());
    std::transform( m_vec.begin(), m_vec.end(), new_vec.begin(), f);
    return augmented_vector < T > ( new_vec );
  }

  T inner_product(T value)
  {
    return std::inner_product( m_vec.begin(), m_vec.end(), m_vec.begin(), value);
  }
};

int main()
{
  augmented_vector<int> v;
  v.push_back(0);
  v.push_back(1);

  auto val = v
    .transform([](auto i) { return i + 2; })
    .transform([](auto i) { return i * 3; })
    .inner_product(0);

  std::cout << val << '\n';
}

或使用D programming language。它有universal function call syntax

import std.algorithm : fold, map;
import std.stdio : writeln;

void main()
{
    auto v = [0, 1];
    auto x = v
        .map!(a => a+2)
        .map!(a => a*3)
        .fold!((a,b) => a + b^^2)(0);
    writeln(x);
}

答案 1 :(得分:0)

包装函数,在包装器函数中提供样板:

template<typename Container, typename Transform>
void transform_container(Container & container, Transform transform) {
  std::transform(std::begin(container), std::end(container),
                 std::begin(container), /* requires output iterator */
                 transform);
}

template<typename T, typename Container>
auto inner_product_self(Container&& container, T initial) {
  return std::inner_product(std::begin(container), std::end(container),
                            std::begin(container),
                            initial);
}

然后您的代码变为:

int main() {
  std::vector<int> v(2);
  std::itoa(std::begin(v), std::end(v), 0);

  transform_container(v, [](auto i) { return i + 2; });
  transform_container(v, [](auto i) { return i * 3; });

  auto result = inner_product_self(container, 0);

  std::cout << "result: " << result;
}

(Live on ideone)

你没有被束缚到面向对象的编程!