A convenient way to convert a vector <string> to a vector <double>

Is there a convenient way in C ++ to convert a vector to a vector, different from using the conversion algorithm and istringstream?

Many thanks for your help!

+5
source share
1 answer

lexical_cast pretty "comfortable."

for(size_t i = 0; i < vec.size(); ++i) {
  vec2.push_back(boost::lexical_cast<double>(vec[i]));
}

Of course, this gets 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!

atofmay also suit your needs, be sure to include cstdlib:

std::transform(strings.begin(), strings.end(), std::back_inserter(doubles), 
               [](const std::string& x) { return std::atof(x.c_str()); });
+9
source

All Articles