Convert vector of strings to vector of integers in C++
This post will discuss how to convert a vector of strings to a vector of integers in C++.
The std::transform
standard algorithm applies an operation to each of the elements in the specified range and returns the result stored in another range. It defined in the <algorithm>
header. This post provides an overview of some of the available alternatives to accomplish this with the std::transform
algorithm.
1. Using stoi()
function
Starting with C++11, you can use the stoi
function to convert a string to an int, defined in the <string>
header file. It throws std::invalid_argument
if the string cannot be parsed. However, it can extract the integer value 1
from the strings like 1s
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<std::string> strings = {"1", "2", "3", "4"}; std::vector<int> ints; std::transform(strings.begin(), strings.end(), std::back_inserter(ints), [&](std::string s) { return stoi(s); }); for (auto &i: ints) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3 4
2. Using boost::lexical_cast
If you use the boost library in your project, you may use the boost::lexical_cast function for converting a string to an integer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <vector> #include <algorithm> #include <boost/lexical_cast.hpp> int main() { std::vector<std::string> strings = {"1", "2", "3", "4"}; std::vector<int> ints; try { std::transform(strings.begin(), strings.end(), std::back_inserter(ints), [&](std::string s) { return boost::lexical_cast<int>(s); }); } catch (const boost::bad_lexical_cast &) { // invalid input - string is not numeric } for (auto &i: ints) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3 4
3. Using String Streams
Another option is to use the string stream to easily convert an integer to a std::string
. The following C++ program demonstrates its usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <vector> #include <algorithm> #include <sstream> int main() { std::vector<std::string> strings = {"1", "2", "3", "4"}; std::vector<int> ints; std::transform(strings.begin(), strings.end(), std::back_inserter(ints), [&](std::string s) { std::stringstream ss(s); int i; ss >> i; return i; }); for (auto &i: ints) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3 4
That’s all about converting a vector of strings to a vector of integers in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)