STL name for the "map" functional programming function

Paul Nathan picture Paul Nathan · Aug 27, 2010 · Viewed 16.5k times · Source

I would like to be able to write something like

char f(char);
vector<char> bar;
vector<char> foo = map(f, bar);

The transform function appears to be similar, but it will not autogenerate the size of the resultant collection.

Answer

AraK picture AraK · Aug 27, 2010

You can use std::back_inserter in <iterator>, although providing the size in front is more efficient. For example:

string str = "hello world!", result;
transform(str.begin(), str.end(), back_inserter(result), ::toupper);
// result == "HELLO WORLD!"