使用stringstream将字符串转换为整数的效率如何?

4
下面的代码比(或比较、或同等)以下代码更有效吗?
make substring from cursor
make stringstream from substring
extract integer using stream operator

?(编辑问题)或者它比以下的方法更(或者少,或者一样)高效:

std::stoi

? 和为什么?

这个函数能否更有效率?

(这个类将以下内容引入作用域:)

std::string expression  // has some numbers and other stuff in it
int cursor              // points somewhere in the string

代码:

int Foo_Class::read_int()
{
    /** reads an integer out of the expression from the cursor */

    // make stack of digits
    std::stack<char> digits;

    while (isdigit(expression[cursor]))  // this is safe, returns false, for the end of the string (ISO/IEC 14882:2011 21.4.5)
    {
        digits.push(expression[cursor] - 48);  // convert from ascii
        ++cursor;
    }

    // add up the stack of digits
    int total = 0;
    int exponent = 0;  // 10 ^ exponent
    int this_digit;

    while (! digits.empty())
    {
        this_digit = digits.top();
        for (int i = exponent; i > 0; --i)
            this_digit *= 10;
        total += this_digit;

        ++exponent;
        digits.pop();
    }

    return total;
}

我知道它不能处理溢出。

我知道有人可能会提到魔术数字。

我尝试使用pow(10, 指数)并得到了不正确的结果。我猜测是因为浮点运算,但不确定原因,因为所有数字都是整数。

2个回答

2

从阅读该链接(std::stoi)来看,似乎我不能以前导0开始,否则它会认为这个数字是八进制。这是正确的吗? - beauxq
@beauxq 不,这个规则只适用于将基数设置为08的情况。默认基数是10,所以你应该没问题。 - Galik

1
我在这个页面上找到了很多信息: http://www.kumobius.com/2013/08/c-string-to-int/ 正如Galik所说,与其他所有东西相比,std::stringstream非常慢。
std::stoi比std::stringstream快得多。
手动编写的代码仍然可能更快,但正如已经指出的那样,它并不执行所有错误检查,并且可能存在问题。
该网站还改进了上面的代码,将总数乘以10,而不是在将数字添加到总数之前乘以它(按顺序而不是反向,在堆栈中)。这样可以减少乘以10的次数。
int Foo_Class::read_int()
{
    /** reads an integer out of the expression from the cursor */

    int to_return = 0;

    while (isdigit(expression[cursor]))  // this is safe, returns false, for the end of the string (ISO/IEC 14882:2011 21.4.5)
    {
        to_return *= 10;
        to_return += (expression[cursor] - '0');  // convert from ascii
        ++cursor;
    }

    return to_return;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接