Hi,

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

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;

    vs.push_back("1");
    vs.push_back("2");
    vs.push_back("3");
    vs.push_back("4");
    vs.push_back("5");

    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.

commented: This will be a good post to refer to in the future (but I've come to expect that). +26
commented: Good job +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.