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