C++语句可以简化

C++ Statement can be simplified

本文关键字:语句 C++      更新时间:2023-10-16

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

bool UnsortedList::isInTheList(float item) {
    for (int i = 0; i < length; i++) {
        if (data[i] == item) {
            return true;
        }
        return false;
    }
}

但是,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.

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

bool UnsortedList::isEmpty() {
    return (length == 0);
}

但是,由于现在涉及迭代,我无法在前者中提出简化的陈述。任何帮助都非常感谢。谢谢。

修复

您的return false应移出for环。


由于您不小心将其放入for循环中,因此此迭代永远不会第二次执行。

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

return data[0] == item;

这显然不是你想要的。所以实际上这只是一个单行的转变,让它正确。

为什么不使用STL?

inline bool UnsortedList::isInTheList(float item) {
    return std::find(data, data+length, item) != data+length;
}

如果找到元素,std::find返回指向元素的迭代器,如果未找到任何内容,则返回等于最后一个项的迭代器(即恰好传递的第二个参数(。您可以使用简单的相等性检查来确定是否找到一个。

您实际上是在循环中迭代一次后返回的。这是编译器的评论。您的代码可以通过轻松编写以下内容来简化:

bool UnsortedList::isInTheList(float item) {
    if (length != 0) {
        return data[0] == item;
    }
}

请注意,这仍然是未定义的行为 (UB(。您的所有执行路径中都没有return。如果你的列表为空,你永远不会进入循环,这会导致一个 UB,因为没有 return 语句,但函数必须返回一个 bool

我想,你的意图是,写这样的东西。

bool UnsortedList::isInTheList(float item) {
    for (int i = 0; i < length; i++) {
        if (data[i] == item) {
            return true;
        }
    }
    return false;
}

return false;移出您的for loop,您会没事的(仍然有更好的方法来实现这一点,但这是另一个主题(。