Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++;
    }
}
like image 905
RnD Avatar asked Jan 31 '12 12:01

RnD


3 Answers

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
}
like image 113
Mankarse Avatar answered Oct 16 '22 08:10

Mankarse


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++;
        }
    }
}
like image 32
hmjd Avatar answered Oct 16 '22 09:10

hmjd


You could simply use the std::count algorithm.

auto counter = std::count( skirt, skirt+skirt_size );
like image 3
Klaim Avatar answered Oct 16 '22 08:10

Klaim