How do I convert vector of strings into vector of integers in C++?

前端 未结 7 2046
甜味超标
甜味超标 2021-01-23 01:10

I have a vector of strings. Need help figuring out how to convert it into vector of integers in order to be able to work with it arithmetically. Thanks!

#include         


        
7条回答
  •  一生所求
    2021-01-23 01:36

    What about:

    #include 
    #include 
    
    template
    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);
    }
    

    It can convert vector into vector, and also other container into container2, e.g.: list -> list.

    Full code:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    template
    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);
    }
    
    template
    std::vector& operator<<(std::vector& v, T2 t)
    {
        v.push_back(T(t));
        return v;
    }
    
    main(int argc, char *argv[])
    {   
        std::vector v1;
        v1 << "11" << "22" << "33" << "44";
        std::cout << "vector: ";
        std::copy(v1.begin(), v1.end(), std::ostream_iterator(std::cout, ", "));
        std::cout << std::endl;
    
        std::vector v2;
        castContainer(v1, v2);
    
        std::cout << "vector: ";
        std::copy(v2.begin(), v2.end(), std::ostream_iterator(std::cout, ", "));
        std::cout << std::endl;
    }
    

提交回复
热议问题