我正在编写一个简单的函数,它迭代数组中的元素。如果找到了元素,则返回或打印"找到的元素",如果没有,则返回未找到的值。
我现在脑子一片空白。帮助
#include<iostream>
using namespace std;
int main(){
int arr[] = {1,11,111};
int size = sizeof(arr)/sizeof(arr[0]);
int option = 999;
int i = 0;
if(arr[i] != ' '){
for (i = 0; i < size; i++){
if(arr[i] == option){
cout << "found" << endl;
break;
} else {
continue;
}
}
cout << "not found" <<endl;
}
return 0;
}
它同时返回已找到和未找到。
您可以得到这两个输出,因为这就是您的代码所做的。找到匹配项后,输出"find",然后break
循环,继续执行程序的其余部分。然后,无论循环做了什么或没有找到什么,您无条件地输出"未找到"。
有几种方法可以解决这个问题。
在中断循环之前设置一个标志,直到循环结束才输出:
#include <iostream>
using namespace std;
int main(){
int arr[] = {1,11,111};
int size = sizeof(arr)/sizeof(arr[0]);
int option = 999;
bool found = false;
if (arr[i] != ' '){
for (int i = 0; i < size; i++){
if (arr[i] == option){
found = true;
break;
}
}
}
if (found)
cout << "found" << endl;
else
cout << "not found" << endl;
return 0;
}
或者简单地说,当找到匹配时立即return
:
#include <iostream>
using namespace std;
int main(){
int arr[] = {1,11,111};
int size = sizeof(arr)/sizeof(arr[0]);
int option = 999;
if (arr[i] != ' '){
for (int i = 0; i < size; i++){
if (arr[i] == option){
cout << "found" << endl;
return 0;
}
}
}
cout << "not found" << endl;
return 0;
}
或者不要手动搜索,而是使用标准的std::find()
算法:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int arr[] = {1,11,111};
int size = sizeof(arr)/sizeof(arr[0]);
int *arrEnd = &arr[size];
int option = 999;
if (find(arr, arrEnd, option) != arrEnd)
cout << "found" << endl;
else
cout << "not found" << endl;
return 0;
}