Using boost::lexical_cast with std::transform
Asked Answered
S

1

5

g++ doesn't like:

vector<int> x;
x += 1,2,3,4,5;

vector<string> y(x.size());
transform(x.begin(), x.end(), y.begin(), lexical_cast<string>);

The error message is:

error: no matching function for call to 'transform(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> >*, std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, <unresolved overloaded function type>)'

Which clearly indicates there is an issue with lexical_cast as the last argument to transform... Is there a way to avoid writing a function object that wraps lexical_cast?

Thanks!

Strychnic answered 13/6, 2011 at 20:14 Comment(1)
Off the top of my head, you probably need lexical_cast<string, int> since there is no argument deduction for the second template argument. lexical_cast might be overloaded, though, which would then require you to use a cast to disambiguate which one you want.Gavra
S
7

This is untested, but you could try:

transform(x.begin(), x.end(), y.begin(), lexical_cast<string, int>);

lexical_cast is a template with two template parameters. Normally the second one is deduced from type deduction from the argument, but you aren't providing an argument, so you need to explicitly specify it.

Senghor answered 13/6, 2011 at 20:20 Comment(1)
Makes sense. I should have seen that. Thanks!Strychnic

© 2022 - 2024 — McMap. All rights reserved.