I would like to know if there is an elegant way or a built-in function to convert vector<double>
to vector<string>
. What I've done is simple
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> doubeVecToStr(const std::vector<double>& vec)
{
std::vector<std::string> tempStr;
for (unsigned int i(0); i < vec.size(); ++i){
std::ostringstream doubleStr;
doubleStr << vec[i];
tempStr.push_back(doubleStr.str());
}
return tempStr;
}
int main( int argc, char* argv[] )
{
std::vector<double> doubleVec;
doubleVec.push_back(1.0);
doubleVec.push_back(2.1);
doubleVec.push_back(3.2);
std::vector<std::string> doubleStr;
doubleStr = doubeVecToStr(doubleVec);
for (unsigned int i(0); i < doubleStr.size(); ++i)
std::cout << doubleStr[i] << " ";
std::cout << std::endl;
return 0;
}
There are many ways, but a standard solution is to use
std::transform
with a lambda usingstd::to_string
for the conversion :And you can wrap that in a function template to make it work with any Standard compliant container :
Or in C++14, with a generic lambda :
And call it with any container (i.e. it works with
std::list<int>
, for instance) :Notes :
to_string
function template :Example:
And use it in a similar way :
reserve()
the memory in the output vector to avoid reallocations duringstd::transform()
:e.g. do this :
Live demo
In general, if you have a container of
T
and want to create a container ofU
from the container ofT
, as others have mentioned the algorithm to look for isstd::transform
.If you are not using C++ 11, Here is
std::transform
usage:Output:
1 2.1 3.2
Using
copy
andostream_iterator
: