Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert <vector><string> TO <vector><int> C++, Win32

Tags:

c++

string

vector

Is there some method to convert a vector to a vector in C++, win32?

I've got this string vector with numbers:

std::vector<std::string> DataNumbers;

I need to convert this vector string into vector integer.

like image 630
Carl Mark Avatar asked Mar 25 '13 16:03

Carl Mark


2 Answers

Given:

std::vector<std::string> DataNumbers;
// Fill DataNumbers
std::vector<int> Data;

You can use std::transform. Use a std::back_inserter to insert the values into the std::vector<int>. For the unary function, use a lambda expression that uses std::stoi to convert the strings to integers.

std::transform(DataNumbers.begin(), DataNumbers.end(), std::back_inserter(Data),
               [](const std::string& str) { return std::stoi(str); });

And here's a version without lambdas (using std::bind instead):

typedef int(*stoi_type)(const std::string&, std::size_t*, int);
std::transform(DataNumbers.begin(), DataNumbers.end(), std::back_inserter(Data),
               std::bind(static_cast<stoi_type>(&std::stoi),
                         std::placeholders::_1, nullptr, 10));
like image 119
Joseph Mansfield Avatar answered Sep 28 '22 00:09

Joseph Mansfield


What about:

#include <algorithm>
#include <boost/lexical_cast.hpp>

template<typename C1, typename C2>
void castContainer(const C1& source, C2& destination)
{
    typedef typename C1::value_type source_type;
    typedef typename C2::value_type destination_type;
    destination.resize(source.size());
    std::transform(source.begin(), source.end(), destination.begin(), boost::lexical_cast<destination_type, source_type>);
}

It can convert vector<string> into vector<int>, and also other container<T1> into container2<T2>, e.g.: list -> list.

Full code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <boost/lexical_cast.hpp>

template<typename C1, typename C2>
void castContainer(const C1& source, C2& destination)
{
    typedef typename C1::value_type source_type;
    typedef typename C2::value_type destination_type;
    destination.resize(source.size());
    std::transform(source.begin(), source.end(), destination.begin(), boost::lexical_cast<destination_type, source_type>);
}

template<typename T, typename T2>
std::vector<T>& operator<<(std::vector<T>& v, T2 t)
{
    v.push_back(T(t));
    return v;
}

main(int argc, char *argv[])
{   
    std::vector<std::string> v1;
    v1 << "11" << "22" << "33" << "44";
    std::cout << "vector<string>: ";
    std::copy(v1.begin(), v1.end(), std::ostream_iterator<std::string>(std::cout, ", "));
    std::cout << std::endl;

    std::vector<int> v2;
    castContainer(v1, v2);

    std::cout << "vector<int>: ";
    std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
}
like image 22
baziorek Avatar answered Sep 28 '22 01:09

baziorek