C++语句可以简化

fil*_*ble 1 c++ if-statement intellij-idea simplify

为蹩脚的问题道歉.我正在使用Intellij Clion Student许可版本用于我的C++课程.作为实现UnsortedList类的一部分,我们必须编写一个方法isInTheList来查看数组中是否存在元素.类实现如下

bool UnsortedList::isInTheList(float item) {

    for (int i = 0; i < length; i++) {
        if (data[i] == item) {
            return true;
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,ide data[i] == item用弹出的说法显示了一个彩色标记

Statement can be simplified less... (Ctrl+F1) 
This inspection finds the part of the code that can be simplified, e.g. constant conditions, identical if branches, pointless boolean expressions, etc.
Run Code Online (Sandbox Code Playgroud)

对于先前检查列表是否为空的方法,我使用以下简化形式而不是if-else语句.

bool UnsortedList::isEmpty() {
    return (length == 0);
}
Run Code Online (Sandbox Code Playgroud)

但是,现在涉及迭代,我无法在前者中提出简化的陈述.任何帮助深表感谢.谢谢.

Yon*_* Li 7

固定

return false应该被移出for循环外面.


因为你不小心将它放在for循环中,所以这个迭代永远不会再次执行.

因此,您的IDE认为for循环是没有意义的,并建议您将其简化为:

return data[0] == item;
Run Code Online (Sandbox Code Playgroud)

这显然不是你想要的.所以,这只是一个单线转换,以使其正确.