Find if an element exists in C++ array [duplicate]

2019-12-26 03:05发布

问题:

#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 am trying to find if an element exists in array, if it doesn't exist I want to re-type the element and to repeat the whole array and check it. Mine doesn't get it from the start (i=0).

回答1:

There is a standard function called std::find in the header <algorithm>:

#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;
}

Ideone



回答2:

There is the perfect function for that in the standard library - std::any_of - if all you want to know is if something exists.

If you also need access to the found element, then there is std::find or std::find_if.

If you want to know how many times something exists, the standard library has you covered with std::count and std::count_if.



回答3:

Try to make a new variable called cnt and use it like this -

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";