Reputation: 10855
Is there any convenient way in C++ to convert a vector to a vector other than using transform algorithm and istringstream?
Thanks a lot for your help!
Upvotes: 5
Views: 2274
Reputation: 59811
lexical_cast
is quite "convenient".
for(size_t i = 0; i < vec.size(); ++i) {
vec2.push_back(boost::lexical_cast<double>(vec[i]));
}
Of course this becomes even more fun with std::transform
:
std::transform(strings.begin(), strings.end(),
std::back_inserter(doubles),
boost::lexical_cast<double, std::string>); // Note the two template arguments!
atof
could also fit your needs, remember to include cstdlib
:
std::transform(strings.begin(), strings.end(), std::back_inserter(doubles),
[](const std::string& x) { return std::atof(x.c_str()); });
Upvotes: 9