Answer the question
In order to leave comments, you need to log in
C++0: iterating over a container using a callback and returning a result (a la Perl map{})
After many hours of experimenting, I managed to guess only this:
template<typename V, typename Cb> auto apply(V vec, Cb&& callback) -> vector<decltype(callback(*vec.begin()))> { vector<decltype(callback(*vec.begin()))>result; for (auto &e: vec) result.push_back(callback(e)); return result; } // Usage: map<string, string> hash; auto result = apply(hash, [](const pair<string,string>& e) { return e.first + "=>" + e.second; });
Answer the question
In order to leave comments, you need to log in
std::transform(vec.begin(), vec.end(), std::back_inserter(result), callback)
for_each iterates, but DOES NOT RETURN the result, but applies it "in place".
std::transform works with iterators (i.e. it doesn't return anything either).
So that's not it.
I understand that it can be written in 2 lines (first, define the result array empty, and then fill it through for_each or transform). But it’s ugly, I want it, like in Perl - cout<<join(apply(hash, [](const pair<string,string>& e) { return e.first + "=>" + e.second; }), "\n");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question