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++;
    }
}
RnD
  • 1,019
  • 5
  • 23
  • 49

3 Answers3

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
}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
3

You could simply use the std::count algorithm.

auto counter = std::count( skirt, skirt+skirt_size );
Klaim
  • 67,274
  • 36
  • 133
  • 188
  • 1
    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. – underscore_d Jul 18 '17 at 18:35
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++;
        }
    }
}
hmjd
  • 120,187
  • 20
  • 207
  • 252