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.

Download  Run Code

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.

Download Code

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:

Download  Run Code

Output:

1 2 3 4

That’s all about converting a vector of strings to a vector of integers in C++.