开发者

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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜