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