Let's say (for simplicity) that I want to pass collection to method, the method will apply some func
to every element of collection and return this collection. E.g. in C# this will looks like this
IEnumerable<Tout> Transform<Tin, Tout>(IEnumerable<Tin> collection,
Func<Tin, Tout> func)
{
return collection.Select(x => func(x));
}
My goal is to write equivalent function in C++. According to this question I should pass two iterators to function which will represent boundaries of input collection. This solves problem of passing collection. But how to return collection?
I was thinking that I should apply same logic and return pair of iterator from function which will represent returning collection.
Here is how I tried to write equivalent function:
template<typename ForwardIterator, typename ReturnIterator>
std::pair<ReturnIterator, ReturnIterator> Transform(
ForwardIterator begin, ForwardIterator end,
std::function <
typename std::iterator_traits<ReturnIterator>::value_type
(typename std::iterator_traits<ForwardIterator>::value_type)
> func)
{
using InputType = std::iterator_traits<ForwardIterator>::value_type;
using RetType = std::iterator_traits<ReturnIterator>::value_type;
std::vector<RetType> ans;
std::transform(begin, end, std::back_inserter(ans),
[&](InputType el) -> RetType { return func(el); } );
return { std::begin(ans), std::end(ans) };
}
int main()
{
// Simple example -> converts every int to string from inputCollection
std::vector<int> inputCollection = { 1,2,3 };
auto retCollecction = Transform<std::vector<int>::iterator, std::vector<std::string>::iterator>
(std::begin(inputCollection),
std::end(inputCollection),
[](int el)-> std::string {return std::to_string(el); });
}
Obviously this is not good since output collection is disposed as soon as I exit function and iterators points to nothing. So, how to fix this, and what should be the best way to write this in C++.
Note: I don't want to pass and return vector<T>
or some other specific collection. I would like a general approach which can deal with any type of collections.