user156857
user156857

Reputation:

Comparing numbers to be sure they are unique?

I have a program where you enter 5 different numbers into an array. I have been having trouble trying to figure out how to make sure that a number is not entered more than once. Could somebody please help me out, or at least point me in the right direction? It's in C++ if that helps at all.

Upvotes: 0

Views: 153

Answers (3)

ludesign
ludesign

Reputation: 1373

You have the array so you only need to loop through it and check if current number matches any of the numbers in the array, if so, return true on first match and skip the number.

Below is some example code:

// pass the array and the number you are checking for existence
int isRepeating(int *array, int unique)
{
    int i, l = sizeof(array) / sizeof(int); // find size of the array

    // loop thru the array and match any value
    for (i = 0; i < l; i++)
    {
        // if matches, return positive
        if (a[i] == unique) return true;
    }

    // otherwise return negative
    return false;
}

int main(int argc, char *argv[])
{
    // out array of existing numbers
    int array[5] = {1, 2, 3, 4, 5};

    // the number we want to insert
    int nextOne = 3;

    // we check it its already in existence, if so, take appropriate actions
    if (isRepeating(array, nextOne)) {
        std::cout << "Oops, number " << nextOne << " is already in existence." << std::endl;
    }

    // your logic here

    return 0;
}

p.s. I really like the set() solution.

Upvotes: -2

wmorrell
wmorrell

Reputation: 5307

Well, one way is to run a check as you add each number to the array. So if you have an existing array of 3 8 15 9 and before inserting the number, check that it is not equal to any of the previous entries.

Upvotes: 0

Matthew Iselin
Matthew Iselin

Reputation: 10670

You could use a std::set, or (depending on what the numbers are used for), a std::map.

std::set seems like your best bet here.

Upvotes: 3

Related Questions