C++语句可以简化
C++ Statement can be simplified
为蹩脚的问题道歉。我正在使用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
,您会没事的(仍然有更好的方法来实现这一点,但这是另一个主题(。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 我似乎对if/else的基本语句有问题:/
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- c++:定义if语句中的模板
- 主线的等价语句是什么