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

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

    Use boost::lexical_cast. And surround it with try-catch block.

    try
    {
       for (size_t i=0; i(vectorOfStrings[i]));
       }
    }
    catch(const boost::bad_lexical_cast &)
    {
        //not an integer 
    }
    

    Or you can use Boost.Spirit parser (which someone claims is faster than even atoi()) as:

    int get_int(const std::string & s)
    {
        int value = 0;
        std::string::const_iterator first = s.begin();
        bool r = phrase_parse(first,s.end(),*int_[ref(value)=_1], space);
        if ( !r || first != s.end()) throw "error"; 
        return value;
    }
    
    //Usage
    int value = get_int("17823");
    std::cout << value << std::endl; //prints 17823
    

    The full demo using your code : http://ideone.com/DddL7

提交回复
热议问题