vendredi 29 mai 2015

C++ map vector of one type to another using lambda

I have a bit of code that looks like

B Convert(const A& a) { 
  B b;
  // implementation omitted.
  return b;
}

vector<B> Convert(const vector<A>& to_convert) {
  vector<B> ret;
  for (const A& a : to_convert) {
    ret.push_back(Convert(a));
  }
  retun ret;
}

I was trying to rewrite this using lambdas but the code does not look more concise or more clear at all:

vector<B> Convert(const vector<A>& to_convert) {
  vector<B> ret;
  std::transform(to_convert.begin(), 
                 to_convert.end(),
                 ret.begin(),
                 [](const A& a) -> B { return Convert(a); });
  retun ret;
}

What I would really like to do is something like:

vector<B> Convert(const vector<A>& to_convert) {
  return map(to_convert, [](const A& a) -> B { return Convert(a); });
}

Where map is a functional style map function that could be implemented as:

template<typename T1, typename T2>
vector<T2> map(const vector<T1>& to_convert, 
               std::function<T2(const T1&)> converter) {
  vector<T2> ret;
  std::transform(to_convert.begin(), 
                 to_convert.end(),
                 ret.begin(),
                 converter);
  retun ret;
}

Obviously the above is limited because it only works with vector, ideally one would want similar functions for all container types. At the end of the day, the above is still not better than my original code.

Why isn't there something like this (that I could find) in the stl?

Aucun commentaire:

Enregistrer un commentaire