2015-05-15 24 views
10

Próbuję przekonwertować vector<int> na vector<string>. Używając std::transform użyłem std::to_string do konwersji int na string, ale wciąż pojawia się błąd. Oto mój kodPrzekształć wektor int na wektor str

#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); 
} 

ale dostaję ten błąd

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... 

Odpowiedz

13

std::to_string jest przeciążony funkcja, więc trzeba zapewnić obsadę disambiguate

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

lub użyć a lambda:

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

możesz wydać Leżąc, jak działa obsada. –

+0

@gauravsehgal Wrzucam go do wskaźnika do typu funkcji, który pobiera argument "int" i zwraca 'std :: string'. Ponieważ OP ma "wektor ", jest to odpowiednie przeciążenie z listy, do której dołączyłem powyżej. – Praetorian

+1

@gauravsehgal Typ w rzutowaniu jest tego samego typu co przeciążenie 'to_string' dla' int'. Jego jedynym skutkiem jest to, że określa, które przeciążenie chcesz. Możesz go zobaczyć jako ręczną rozdzielczość przeciążania. – molbdnilo