【发布时间】:2015-03-10 14:48:08
【问题描述】:
我正在写一个函数,到目前为止我有
size_t CalculusWizard :: _grabDecimal ( std::string::const_iterator it1, std::string::const_iterator it2, std::string & ds )
{
/*
it1: iterator to the beginning of the decimal string
it2: iterator to the 1-off-the-end of the range of which the decimal can span
ds: string to hold the decimal representation
Reads the decimal in the range [it1, it2) into the string ds
*/
ds.clear();
size_t ncp = 0; /* # of characters parsed */
if (it1 != it2 && *it1 == '-') ds.push_back(*it1++); /* Handle possible minus sign */
bool foundDot = false;
while (it1 != it2)
{
if (*it1 == '.')
{
if (foundDot) break;
else foundDot = true;
}
else if (_digMap.count(*it1) > 0)
{
// ...
}
else
{
break;
}
++it1;
}
return ncp;
}
我的主要问题与if (it1 != it2 && *it1 == '-') 状态有关。我的意思是它是一种更紧凑的写作方式
if (it1 != it2)
{
if (*it == '-') // ...
}
因为it2 可能不在字符串的末尾,我想避免意外行为。但我想知道如果
(1) 我写它的方式被认为是可读的
(2) 它可能会导致问题,因为它假定由&& 分隔的语句从左到右有条件地执行。
希望对计算机科学概念有更深入了解的人可以向我解释这一点。
作为奖励,有没有人有更好的方法来做我试图用这个功能做的事情?我要做的就是获取包含在字符串中的十进制表示,同时跟踪在获取小数时解析的字符数。我无法使用stod,因为我丢失了我需要的信息。
【问题讨论】:
-
@TartanLlama:不,这完全不相关。优先级决定了表达式的解析方式,而不是它的运行方式。即使我们知道 LHS 是首先评估的,我们也无法回答这个问题。这里的关键是,如果 LHS 为假,则根本不会评估 RHS。
标签: c++ algorithm compilation logic machine-code