tags:

views:

103

answers:

2

I would like to be able to write something like

char f(char);
vector<char> bar;
vector<char> foo = map(f, bar); //Strikingly functional.

in the STL.

But, as we all know, the STL has the map class as a collection.

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

+8  A: 

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!"
AraK
+1 -- You can use `std::vector<t>::reserve` in order to remove the efficiency penalty as well.
Billy ONeal
A: 

To make this work, you'll need the following observations:

  1. To make the assignment efficient, the map function should not do the work. Instead, it should save its arguments in a temporary object (in your case, that would be an instance of class map::result<char(*)(char), vector<char> >)
  2. This map::result temporary should have an template <typename T> operator T conversion.
  3. When the map::result is assigned to a std::vector<char>, this conversion is the only viable.
  4. In the conversion operator class map::result<char(*)(char), vector<char> >::operator vector<char> you have the input and return type, and the mapping function. At this point you can effectively transform the inputs.
MSalters