如何检查数组中的所有值是否相同?

时间:2021-03-23 11:46:50

标签: arrays c if-statement

假设我有一个数组 short int check[10] = {1,1,1,1,1,1,1,1,1};
我想检查所有元素是否相同。
我在 stackoverflowgoogle 中都找不到答案,但我在 C++ 中遇到过这段代码。

bool aresame(int a[], int n)
{
    int i;
    unordered_map<int, int> m;

    for (i = 0; i < n; i++)
    {
        m[a[i]]++;
    }
    if (m.size() == 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

稍微调整一下,结果是巨大的错误。
我的尝试是使用if's,但这非常不专业。
不妨知道,有没有其他方法可以做吗?

5 个答案:

答案 0 :(得分:3)

正如 Gerhardh 在评论中指出的那样,使用 if 没有任何不专业的地方。此代码应该可以工作:

#include <stdbool.h>

bool are_same(int *arr, unsigned int len)
{
    for (int i = 1; i < len; ++i)
        if (arr[0] != arr[i])
            return false;
    return true;
}

您可以像这样调用函数 are_same

int arr[] = {1, 1, 1, 1, 1};
unsigned int len = sizeof(arr) / sizeof(int);
printf("The elements in the array are %s.\n",
       are_same(arr, len) ? "all the same" : "not all the same");

答案 1 :(得分:3)

if 非常好,没有任何不专业

我要注意,在short int check[10] = {1,1,1,1,1,1,1,1,1};中只有9个元素是1,最后一个元素会被初始化为0,所以这个检查总是false,如果你省略了大小ie check[] = {1,1,1... 你不会有这个问题,因为数组的大小将由初始化器中的元素数量推导出来。

#include <stdio.h>
#include <stdbool.h>

bool aresame(short int a[], size_t n) // added value to check
{
    for (size_t i = 1; i < n; i++)
    {
        if(a[i] != a[0])
            return false; // if a different value is found return false
    }
    return true; // if it reaches this line, all the values are the same
}

int main()
{
    short int check[]={1,1,1,1,1,1,1,1,1};
    printf("%s", aresame(check, sizeof check / sizeof *check) ? "true" : "false");
}

Live demo

答案 2 :(得分:1)

如果你不喜欢 if 语句,那么试试这个:

bool aresame(int a[], int n) {
    int i = 0;
    while(i<n && a[i]==a[0]) 
        i++;
    return i == n;
}

无需使用额外的本地存储,只需循环直到看到不相同的元素。如果你到达终点,一切都很好。否则不行。

请看这里:https://godbolt.org/z/8r6YK6W34

答案 3 :(得分:1)

为了完整起见,这里有一个递归版本(没有明确的 ifs):

bool aresame(int a[],int n){
    return (n <= 1) || (a[0] == a[n-1] && aresame(a, n-1));
}

答案 4 :(得分:1)

假设没有填充位的二进制补码,这是一个快速而肮脏的无 if 实现:

#include <stdbool.h>
#include <string.h>

bool are_same(const int *arr, size_t n) {
    return n == 0 || !memcmp(arr, arr + 1, (n - 1) * sizeof(*arr));
}

您可以推广此方法以检查数组是否包含长度为 r 的重复序列:

#include <stdbool.h>
#include <string.h>

bool is_repeating(const int *arr, size_t n, size_t r) {
    return n <= r || !memcmp(arr, arr + r, (n - r) * sizeof(*arr));
}
相关问题