RnD
RnD

Reputation: 1069

C++ check if element exists in array

I've found a lot of topics like this, but it was kinda too complicated for me.

How to check if element exists in an array?

first I declare an array and put values in it

for(int l=0;l<=21;l++){
        skirt[l]=l;
    }

and then with another for I'd like to check if any element which exist in other array is in array skirt[];

Is there a way to write it something like this?

for(int k=0;k<=n;k++){
    if(skaiciai[k]!=skirt[k]){
        counter++;
    }
}

Upvotes: 6

Views: 35512

Answers (3)

Mankarse
Mankarse

Reputation: 40613

The best way to do this would be to use standard algorithm, rather than a handwritten loop:

if (std::find_first_of(
        skirt, skirt + skirt_size,
        skaiciai, skaiciai + skaiciai_size)
    != skirt + skirt_size)
{
    //skirt contained an element from skaiciai
}

Upvotes: 5

hmjd
hmjd

Reputation: 121961

The loop:

for(int k=0;k<=n;k++){
    if(skaiciai[k]!=skirt[k]){
        counter++;
    }
}

would only compare elements at the same index in the arrays. Nested for loops are required with the outer for loop iterating over the elements in one array and the inner for loop iterating over elements in the other array:

for (int k_skirt = 0; k_skirt <= n; k_skirt++)
{
    for (int k_skaiciai = 0; k_skaiciai <= n; k_skaiciai++)
    {
        if(skaiciai[k_skaicia] == skirt[k_skirt]){
            counter++;
        }
    }
}

Upvotes: 3

Klaim
Klaim

Reputation: 69672

You could simply use the std::count algorithm.

auto counter = std::count( skirt, skirt+skirt_size );

Upvotes: 3

Related Questions