Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convenient way to convert vector<string> to vector<double>

Tags:

c++

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!

like image 928
Qiang Li Avatar asked Aug 11 '11 01:08

Qiang Li


1 Answers

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()); });
like image 94
pmr Avatar answered Sep 25 '22 02:09

pmr