使用boost :: lexical_cast和std :: transform

问题描述

|| g ++不喜欢:
vector<int> x;
x += 1,2,3,4,5;

vector<string> y(x.size());
transform(x.begin(),x.end(),y.begin(),lexical_cast<string>);
错误消息是:
error: no matching function for call to \'transform(__gnu_cxx::__normal_iterator<int*,std::vector<int,std::allocator<int> > >,__gnu_cxx::__normal_iterator<int*,__gnu_cxx::__normal_iterator<std::basic_string<char,std::char_traits<char>,std::allocator<char> >*,std::vector<std::basic_string<char,std::allocator<char> >,std::allocator<std::basic_string<char,std::allocator<char> > > > >,<unresolved overloaded function type>)\'
这清楚地表明lexical_cast作为转换的最后一个参数存在问题。是否有办法避免编写包装lexical_cast的函数对象? 谢谢!     

解决方法

        这未经测试,但是您可以尝试:
transform(x.begin(),x.end(),y.begin(),lexical_cast<string,int>);
lexical_cast
是带有两个模板参数的模板。通常,第二个参数是从参数的类型推导推导出的,但是您没有提供参数,因此需要显式指定它。