查找数组中是否存在C++元素

Find if an element exists in C++ array

本文关键字:C++ 元素 存在 是否 数组 查找      更新时间:2023-10-16
#include <iostream>
float x[10], k;
int n, i;
cout<<"N= "; cin>>n;
for (i=0; i<n; i++){
cout<<"x["<<i<<"]= ";
cin>>x[i];
}
cout<<"Array's elements: ";
for (i=0; i<n; i++)
cout<<x[i]<<", ";
cout<<endl<<"K= "; cin>>k;
for(i=0; i<n; i++)
if(x[i]!=k){
cout<<endl<<"K doesn't exist in array.";
cout<<endl<<"K= "; cin>>k;
}

我正在尝试查找数组中是否存在一个元素,如果它不存在,我想重新键入该元素并重复整个数组并检查它。 我的从一开始就没有得到它(i = 0(。

标准库中有一个完美的函数 - std::any_of - 如果你想知道的只是是否存在某些东西。

如果你还需要访问找到的元素,那么有std::find或std::find_if。

如果你想知道某物存在多少次,标准库为你提供了std::count和std::count_if。

标头<algorithm>中有一个名为std::find的标准函数:

#include <iostream>
#include <algorithm>
int main() {
int myarray[6]{10, 4, 14, 84, 1, 3};
if (std::find(std::begin(myarray), std::end(myarray), 1) != std::end(myarray))
std::cout << "It exists";
else
std::cout << "It does not exist";
return 0;
}

艾德酮

尝试创建一个名为 cnt 的新变量并像这样使用它 -

for(i=0; i<n; i++)
if(x[i]==k){
++cnt;
}
if (cnt==0)
cout << "k has not occured";
else
cout<<"k has occured"<<cnt<<"times";