c++ - 编译器是否按照您编写它们的相同顺序放置 && 语句的子句?

标签 c++ algorithm compilation logic machine-code

<分区>

我正在写一个函数,到目前为止我有

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,因为我丢失了我需要的信息。

最佳答案

1) 当然...如果其他程序员不可读,该语言就不会有 &&

2) 否 - 它不会造成问题。请注意,&& 运算符是一个“短路”逻辑运算符,左侧先于右侧求值,因此即使是 p && *p = 这样的代码= 2pnullptr 时保证安全。

至于如何改进功能...我建议使用 std::istringstream 从字符串表示中解析数字(使用 std::string::substr 如果你想解析字符串的一部分),那么你可以使用 tellg在流上查看已解析了多少。

更“C”风格的替代方案是使用 strtod - str_end 参数可以捕获第一个未转换字符的位置。

关于c++ - 编译器是否按照您编写它们的相同顺序放置 && 语句的子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28966814/

相关文章:

c++ - 如何将对象(或指针)从 C++ .NET 应用程序发送到 VB 应用程序

c++ - Pimpl习惯用语结合了多个虚拟继承

c++ - 如何在Qt中实现HMAC-SHA1算法

C++ 避免或管理 MSVC 中的循环项目依赖

c++ - 在点数组中找到最小值的算法

Powershell - 使用模块编译

vim - 从 Vim 编译 Actionscript

java - Clauset-Newman-Moore 社区检测实现

algorithm - 在包含点的 Voronoi 图中有效地找到多边形

java - 有没有办法按类跟踪java编译时间?