Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform a vector of int to a vector of str

Tags:

c++

c++11

vector

I'm trying to convert a vector<int> to a vector<string>. Using std::transform I used std::to_string to convert the int to string but I keep getting an error. Here's my code

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

but I'm getting this error

 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...
like image 870
peanutbutterjelly Avatar asked May 15 '15 18:05

peanutbutterjelly


People also ask

How do you make a vector into a string?

Convert Vector to String using toString() function To convert elements of a Vector to Strings in R, use the toString() function. The toString() is an inbuilt R function used to produce a single character string describing an R object.

Can you convert a vector to string in C++?

Using std:: accumulate Another option to convert a vector to a string is using the standard function std::accumulate , defined in the header numeric.


1 Answers

std::to_string is an overloaded function, so you'll need to provide a cast to disambiguate

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

Or use a lambda

std::transform(v_int.begin(),v_int.end(),v_str.begin(),
               [](int i){ return std::to_string(i); });
like image 161
Praetorian Avatar answered Sep 26 '22 02:09

Praetorian