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

前端 未结 7 2048
甜味超标
甜味超标 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:37

    The most general way to convert strings to integers is with stringstream and a function template. You can optionally set the base for the conversion if you're dealing with hexadecimal. The boost library would also be helpful in your example.

    #include <iostream>
    #include <string>
    #include <vector>
    
    #include <sstream>
    #include <stdexcept>
    #include <boost/static_assert.hpp>
    #include <boost/foreach.hpp>
    
    /******************************************************************************
     * Handy string to type conversion
     * First parameter is the string to convert
     * Second optional parameter is the number base, e.g. std::hex
     * 
     * Because this is a function template, the compiler will instantiate one
     * instance of the function per type
     *****************************************************************************/
    // the std::dec thingy is actually a function, so extra glue required.
    typedef std::ios_base& (*ios_base_fn)( std::ios_base& str );
    template <class T>
    T strtotype( const std::string& s, ios_base_fn base = std::dec )
    {
        // C++ can't convert 8-bit values, they are *always* treated
        // as characters. :(  At least warn the user.
        // this gives a cryptic error message, but better than nothing.
        BOOST_STATIC_ASSERT( sizeof(T) > 1 );
    
        T val;
        std::istringstream iss(s);
        iss >> base >> val;
        if( iss.fail() )
            throw std::runtime_error( "Error: strtotype(): Can't convert string '" + s + "' to numeric value" );
        return val;
    }
    
    using namespace std;
    
    int main(int argc, char* argv[]) {
    
        vector<string> vectorOfStrings;
        vectorOfStrings.push_back("1");
        vectorOfStrings.push_back("2");
        vectorOfStrings.push_back("3");
    
        for (int i=0; i<vectorOfStrings.size(); i++)
        {
            cout<<vectorOfStrings.at(i)<<endl;
        }
    
        vector<int> vectorOfIntegers;
    
        for( size_t i = 0; i < vectorOfStrings.size(); i++ )
            vectorOfIntegers.push_back( strtotype<int>( vectorOfStrings[i] ));
    
        // or better yet, use boost_foreach
        BOOST_FOREACH( const string& s, vectorOfStrings )
            vectorOfIntegers.push_back( strtotype<int>( s ));
    
        int sum;
        for (int i=0; i<vectorOfIntegers.size(); i++)
        {
            sum += vectorOfIntegers.at(i);
        }
        cout<<sum<<endl;
        cin.get();
    
        return 0;
    }
    

    If you don't want or can't use boost, you can remove the sizeof() check in strtotype. However, be careful never to try to convert to strings to individual bytes. Doing so will fail silently by only converting the first nibble of the byte.

    If you're suing GNU tools, then compile like so:

     g++ -Wall -O3 -I /path/to/boost/include main.cpp
    

    or, if you delete the boost related bits:

     g++ -Wall -O3 main.cpp 
    
    0 讨论(0)
提交回复
热议问题