I was just wondering how to convert a vector<string> to vector<int>. I am using the transform function from <algorithm> but I am not sure what the format is.

vector <string > string;
vector <int> int;
tranform(string.begin(), string.end(), int.begin(), atoi);

Get a compile error. Could anyone tell me whats wrong. Thanks

7 Years
Discussion Span
Last Post by Tom Gunn

atoi is a C function expecting a char*
Perhaps you need to implement a small conversion function which accepts a std::string instead.


You have the right idea, but there are a few problems in the details:

vector <string > string;
vector <int> int;

Naming your variables the same as types is not a good idea. Most of the time it will not work the way you want.

tranform(string.begin(), string.end(), int.begin(), atoi);

First, atoi() does not work on C++ string objects. You need to define another function that does. Second, transform() does not insert new items onto the destination. This call will fail because the int vector does not have room.

Compare your code with this:

#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>

int StrToInt(std::string const& s)
    std::istringstream iss(s);
    int value;

    if (!(iss >> value)) throw std::runtime_error("invalid int");

    return value;

int main()
    std::vector<std::string> vs;
    std::vector<int> vi;


    std::transform(vs.begin(), vs.end(), std::back_inserter(vi), StrToInt);

    std::vector<int>::const_iterator x = vi.begin();
    int sum = 0;

    while (x != vi.end()) sum += *x++;

    std::cout << "Sum: " << sum << '\n';

String streams are a good way to convert between strings and other types because most of the work is already done for you. And when you want transform() to add new items, the back_inserter uses a call to push_back() instead of just assigning to an index.

Votes + Comments
Good job
This will be a good post to refer to in the future (but I've come to expect that).
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.