C++ check if element exists in array
33,441
Solution 1
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++;
}
}
}
Solution 2
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
}
Solution 3
You could simply use the std::count algorithm.
auto counter = std::count( skirt, skirt+skirt_size );
Comments
-
RnD over 4 years
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 arrayskirt[];
Is there a way to write it something like this?
for(int k=0;k<=n;k++){ if(skaiciai[k]!=skirt[k]){ counter++; } }
-
underscore_d almost 7 yearsThis 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.