在数组中查找元素,如果找到则返回Find,否则返回not Find
Find an element in an array, return found if found, else return not found
我正在编写一个简单的函数,它迭代数组中的元素。如果找到了元素,则返回或打印"找到的元素",如果没有,则返回未找到的值。
我现在脑子一片空白。帮助
#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;
}
相关文章:
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- C++ find() 在存储为变量时返回不同的值
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 在数组中查找元素,如果找到则返回Find,否则返回not Find
- find() 没有返回可以使用的 int 值,并且在编译之前给出错误
- std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值
- 由 std::find() 返回的迭代器不可取消引用
- 为什么空 unordered_map.find 不返回 end()?
- C++ std::find() 寻址返回向量的类函数时的意外行为
- std::string::find 返回错误的答案
- std::string::find 总是返回 string::npos 偶数
- GetPrivateProfileStringA 返回"The system cannot find the file specified."即使文件存在
- String.find() 在 C++ 中找不到任何内容时不会返回 -1
- 为什么要对 map::find 应用不存在的键将返回一个C++中第一个值映射大小的迭代器
- std::map中的find()函数返回一个值,尽管没有有效的键
- std :: map find()返回错误
- 自定义类对象的向量的std::find的返回值
- 哪个元素将从 std::multimap::find 返回,同样,std::multiset::find
- 使用 string::find 和 string::substr 拆分字符串的函数返回错误的标记
- c++二进制搜索无论用户类型如何都会返回(find)