工作溶液
您在这里解决的是查找问题。您对输入的值没有任何建议
可能是这样,所以你应该一步一步地尝试每一项。这是一个常见问题。
解决这个问题的第一种方法是使用循环。对于现代 C++ 来说这不是一个好方法。但你也许应该
尝试一下练习。
bool has(int val, int const* arr, size_t size) {
size_t idx = 0;
// Iterates each element of array and checks
// whether the one is equal to the `val`. In
// case of meeting of `val`, the loop stops.
while (idx < size && arr[idx] != val) ++idx;
return idx != size;
}
下面的方式比较方便。实际上,更一般的形式是has
函数已经存在于 C++ 标准库中<algorithm>
标头。它被称为find
。它的作用完全相同,但更好。实际上,有很多功能可以解决常见问题<algorithm>
标头。你必须在任何可以使用的地方使用它。
bool has_(int val, int const* arr, size_t size) {
int const* end = arr + size;
// Now `has_` don't iterate each element and
// checks it. It finds the `val` in range
// between the first element of array and
// the last.
return std::find(arr, end, val) != end;
}
我建议您阅读“优先使用算法调用而不是手写循环”小节。在书中的“STL:容器”部分Herb Sutter 和 Andrei Alexandrescu 的《C++ 编码标准》 https://rads.stackoverflow.com/amzn/click/com/0321113586获得关于为什么使用的直觉<algorithm>
header.
此外,您还可以找到对<algorithm>
header here http://www.cplusplus.com/reference/algorithm/.
您的解决方案中存在错误
让我们考虑您的代码并讨论为什么最终会出现错误。事实上,你只是打错字了。
这是使用的原因之一<algorithm>
标题而不是像你这样的手写循环。
#include<iostream>
#include<conio.h>
using namespace std;
void main()
{
int a[10], found;
for (int i = 0; i<10; i++)
{
cout << "enter value : ";
cin >> a[i];
}
cout << "Enter Searching Value :";
cin >> found;
for (int i = 0; i<10; i++)
{
// Look at here: you compare entered value ten times
// with the value after the last element of array.
if (found == a[10])
{
// In case that you found an entered value in array
// you just continue the loop. You should probably
// break it at this point. This may be achieved by
// using the `brake` operator or the `while` loop.
cout << "Value Found";
_getch();
}
else if (found != a[10])
cout << "Value Not Found";
}
_getch();
}