6

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

3 Answers 3

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

3

You could simply use the std::count algorithm.

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

1 Comment

This would not compile, as you omitted any value or predicate to compare against; no overload of std::count() takes only 2 arguments, as it needs the 3rd to tell it what to count. And it's how to count using nesting that is the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.