To convert a vector of strings to a vector of floats in C++, you can use the `std::stof()` function along with the `std::transform()` algorithm.
In this example,
strVector
.floatVector
.std::transform()
algorithm to apply the std::stof()
function to each element of strVector
and store the result in floatVector
.#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int main() {
std::vector<std::string> strVector = {"1.5", "2.5", "3.5", "4.5", "5.5"};
std::vector<float> floatVector;
floatVector.reserve(strVector.size());
std::transform(strVector.begin(), strVector.end(), std::back_inserter(floatVector), [](const std::string& str) { return std::stof(str); });
for (const auto& num : floatVector) {
std::cout << num << " ";
}
return 0;
}
1.5 2.5 3.5 4.5 5.5
In this tutorial, we learned How to Convert a Vector of Strings to a Vector of Floats in C++ language with well detailed examples.