比较数字以确保它们是独一无二的?

时间:2011-02-05 00:20:44

标签: c++ data-structures

我有一个程序,你可以在一个数组中输入5个不同的数字。我一直在努力弄清楚如何确保一个数字不会被输入多次。有人可以帮助我,或者至少指出我正确的方向?如果它有帮助的话,那就是C ++。

3 个答案:

答案 0 :(得分:3)

您可以使用std::set或(取决于所使用的数字)std::map

std::set似乎是您最好的选择。

答案 1 :(得分:0)

好吧,一种方法是在将每个数字添加到数组时运行检查。因此,如果您有一个3 8 15 9的现有数组,并且在插入数字之前,请检查它是否与之前的任何条目相同。

答案 2 :(得分:-2)

你有数组所以你只需要遍历它并检查当前数字是否与数组中的任何数字匹配,如果是,在第一次匹配时返回true并跳过该数字。

下面是一些示例代码:

// 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。我非常喜欢set()解决方案。