将int的向量转换为str的向量

时间:2015-05-15 18:17:59

标签: c++ c++11 vector

我试图将vector<int>转换为vector<string>。使用std::transform我使用std::to_stringint转换为string,但我一直收到错误消息。这是我的代码

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>

int main(){
    std::vector<int> v_int;
    std::vector<std::string> v_str;

    for(int i = 0;i<5;++i)
        v_int.push_back(i);

    v_str.resize(v_int.size());
    std::transform(v_int.begin(),v_int.end(),v_str.begin(),std::to_string);
}

但我收到此错误

 no matching function for call to 'transform'
        std::transform(v_int.begin(),v_int.end(),v_str.begin(),std::to_string);
        ^~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:1951:1: note: 
      candidate template ignored: couldn't infer template argument
      '_UnaryOperation'
transform(_InputIterator __first, _InputIterator __last, _OutputIterato...
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:1961:1: note: 
      candidate function template not viable: requires 5 arguments, but 4 were
      provided
transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputItera...

1 个答案:

答案 0 :(得分:13)

std::to_string是一个重载函数,因此您需要提供一个强制转换来消除歧义

std::transform(v_int.begin(),v_int.end(),v_str.begin(),
               static_cast<std::string(*)(int)>(std::to_string));

或使用lambda

std::transform(v_int.begin(),v_int.end(),v_str.begin(),
               [](int i){ return std::to_string(i); });