FrakkinShip FrakkinShip - 2 months ago 5
C++ Question

C++: Checking array for duplicates using a value passed into a function

PLEASE DO NOT POST CODE CONTAINING THE ANSWER. I WANT TO ARRIVE AT THE CODE MYSELF.

I have an assignment that asks me to create a set class. This involves creating a function that checks the current values in the array for duplicates based on the value being passed in. For instance,

bool set::contains(const value_type& target) const


would check that target is in the set and return true or false based on whether or not it exists. This function would then be asserted in an insert function that inserts a target value into the set. The issue? Arriving at the code to search through the array and check if the target value is there.

I have the following variables for my class:

data[CAPACITY] //array to store the items, where CAPACITY
//is a const storing the maximum number of items in the array
size_type used //how much of the array is used


I attempted the following for loop and it did not work:

bool set::contains(const value_type& target) const
{
for (int i = 0; i < used; i++)
{
if (target == data[i])
{
return true;
}
else
{
return false;
}
}
}


I figured this would work because it appears I'm iterating through the array by going through how much of the array is used, and then checking each index of the array for the target value. When I test this code in my main function, but the printed numerical value is always 0, or NO.

Any thoughts? I cannot sort the array as we have not learned about that yet.

Answer

The problem is that you return false inside the loop. So you'll return false immediately if the first item in the set is not equal to the one you're looking for. You should wait until you finish the loop -- if you haven't found the item you're searching for yet, then it's not there, so you should return false.

bool set::contains(const value_type& target) const
{
    for (int i = 0; i < used; i++)
    {
        if (target == data[i])
        {
            return true;
        }
    }
    return false;
}
Comments