The Nightman
The Nightman

Reputation: 5759

How to check presence of an element in C++ array

I am a bit stuck as to how to write some code that will check if any positions in a 2D array contain a certain variable.

So imagine a 2D array that is 8x8, and each element has a value of either -1, 0, or 1. I want to continue running code only if both -1 and 1 are found within the array.

My problem is that I only know how to loop through the entire array such that I can get the value of the last element and test whether it would be -1 or 1, rather than testing if any of the array elements are 1 or -1.

I hope the code below illustrates what I am trying to do. Thanks.

for(int x=0; x<8; x++)
{
    for(int y=0; y<8; y++)
    {
        if(array[x][y] == 1)
        {
            stop checking
            oneExists = true;
        }
        if(array[x][y] == -1)
        {
            stop checking
            minusoneExists = true;
        }
        else
        {
            oneExists = false;
            minusoneExists = false;
        }
    }

    if(oneExists==true & minusoneExists==true)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Upvotes: 0

Views: 1508

Answers (4)

Jarod42
Jarod42

Reputation: 217135

Using standard library:

bool contains(const int (&m)[8][8], int value)
{
    return std::any_of(std::begin(m), std::end(m), [value](const auto&a)
    {
        return std::any_of(std::begin(a), std::end(a), [value](int e)
        {
            return e == value;
        });
    });
}

bool contain_one_and_minus_one(const int (&m)[8][8])
{
    return contains(m, 1) && contains(m, -1);
}

Live Demo

Upvotes: 0

Abhishek Ranjan
Abhishek Ranjan

Reputation: 238

how about this.

    for(int x=0; x<8; x++)
    {
        bool flag=true;
        for(int y=0; y<8; y++)
        {
            if(array[x][y]==0)
            {
                flag=false;
                break;
            }
        }

        if(!flag)
            return false;

    }
    return true;

Upvotes: 0

thinker
thinker

Reputation: 211

Something like below would probably do the trick:

oneExists = false;
minusoneExists = false;

for(int x=0; x<8 && ! (oneExists && minusoneExists); x++)
{
    for(int y=0; y<8  && ! (oneExists && minusoneExists); y++)
    {
        if(array[x][y] == 1)
        {
            oneExists = true;
        }
        if(array[x][y] == -1)
        {
            minusoneExists = true;
        }
    }
}

return oneExists && minusoneExists;

Upvotes: 2

feetwet
feetwet

Reputation: 3446

How about this:

bool oneExists = false;
bool minusoneExists = false;
for(int x=0; x<8; x++)
{
    for(int y=0; y<8; y++)
    {
        if(array[x][y] == 1)
        {
            oneExists = true;
        }
        else if(array[x][y] == -1)
        {
            minusoneExists = true;
        }
        if(oneExists && minusoneExists) return true;
    }
}
return false;

Upvotes: 1

Related Questions