c++ - Mapping a vector of one type to another using lambda -


i have bit of code looks like

b convert(const a& a) {    b b;   // implementation omitted.   return b; }  vector<b> convert(const vector<a>& to_convert) {   vector<b> ret;   (const a& : to_convert) {     ret.push_back(convert(a));   }   retun ret; } 

i trying rewrite using lambdas code not more concise or more clear @ all:

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

what like:

vector<b> convert(const vector<a>& to_convert) {   return map(to_convert, [](const a& a) -> b { return convert(a); }); } 

where map functional style map function 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(),                  std::back_inserter(ret),                  converter);   retun ret; } 

obviously above limited because works vector, ideally 1 want similar functions container types. @ end of day, above still not better original code.

why isn't there (that find) in stl?

you said yourself, map not generic enough. std::transform on other hand is, @ cost of more verbose interface. reason map, unlike std::transform forces new allocation, not desirable.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -