Re: mapcar contest
Ian Collins <ian-news@hotmail.com> wrote:
template <typename T,
template <typename X,typename A=std::allocator<X> > class In,
template <typename X,typename A=std::allocator<X> > class Out,
typename Op>
void mapcar( const In<T>& in, Out<T>& out, Op op )
{
typename Out<T>::iterator it(out.begin());
std::insert_iterator< Out<T> > insert(out,it);
std::transform( in.begin(), in.end(), insert, abs );
}
That way of doing it is more "type-safe" in the sense that you will get
more sensical error message in case the parameters are of the wrong type
(although that's debatable, as usually you will only get a very confusing
error of type "mapcar was not declared in this score"). However, it's not
strictly necessary to do it that complicated. This achieves the same thing
with less code:
template<typename In, typename Out, typename Op>
void mapcar(const In& in, Out& out, Op op)
{
std::insert_iterator<Out> insert(out, out.begin());
std::transform(in.begin(), in.end(), insert, op);
}
(If you need the element type for some reason, you can always use
In::value_type and Out::value_type.)