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...
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.
Using std:: accumulate Another option to convert a vector to a string is using the standard function std::accumulate , defined in the header numeric.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With