如何在C++中将字符串向量转换为整数向量?

neb*_*lus 2 c++ string vector

我有一个字符串向量.需要帮助搞清楚如何将其转换为整数向量,以便能够以算术方式使用它.谢谢!

#include <iostream>
#include <string>
#include <vector>
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;

    //HELP NEEDED HERE
    //CONVERSION CODE from vector<string> to vector<int> 

    int sum;
    for (int i=0; i<vectorOfIntegers.size(); i++)
    {
        sum += vectorOfIntegers.at(i);
    }
    cout<<sum<<endl;
    cin.get();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Alo*_*ave 10

有多种方法可以将字符串转换为int.

解决方案1:使用Legacy C功能

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

解决方案2:使用lexical_cast(最合适和最简单)

int x = boost::lexical_cast<int>("12345"); 
Run Code Online (Sandbox Code Playgroud)

环绕try-catch以捕获异常.

解决方案3:使用 C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 
Run Code Online (Sandbox Code Playgroud)


Naw*_*waz 5

使用boost::lexical_cast.用try-catch块包围它.

try
{
   for (size_t i=0; i<vectorOfStrings.size(); i++)
   {
      vectorOfIntegers.push_back(boost::lexical_cast<int>(vectorOfStrings[i]));
   }
}
catch(const boost::bad_lexical_cast &)
{
    //not an integer 
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用Boost.Spirit解析器(有人声称比偶数更快atoi()):

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
Run Code Online (Sandbox Code Playgroud)

使用您的代码的完整演示:http://ideone.com/DddL7