Qiang Li
Qiang Li

Reputation: 10855

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

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

Answers (1)

pmr
pmr

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

Related Questions