下面的代码比(或比较、或同等)以下代码更有效吗?
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, 指数)并得到了不正确的结果。我猜测是因为浮点运算,但不确定原因,因为所有数字都是整数。
0
或8
的情况。默认基数是10
,所以你应该没问题。 - Galik