简体   繁体   English

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

[英]How to check if all values in array are the same?

Lets say I have an array short int check[10] = {1,1,1,1,1,1,1,1,1};假设我有一个数组short int check[10] = {1,1,1,1,1,1,1,1,1}; . .
I want to check if all the element are the same.我想检查所有元素是否相同。
I can't find the answer in stackoverflow nor google , but I've come across this code in C++ .我在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;
    }
}

Adjust a bit, and the result is huge error.稍微调整一下,结果是巨大的错误。
My attempt is using if's but that's very un-professional.我的尝试是使用if's ,但这非常不专业。
Might as well know, is there are any other ways to do it?不妨知道,还有其他方法可以做到吗?

As Gerhardh pointed out in the comments, there is nothing unprofessional about using if .正如Gerhardh在评论中指出的那样,使用if没有什么不专业的。 This code should work:此代码应该可以工作:

#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;
}

You can call the function are_same like this:您可以像这样调用 function 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");

if is perfectly fine, there is nothing unprofessional about it. if完全没问题,没有什么不专业的。

I should note that in short int check[10] = {1,1,1,1,1,1,1,1,1};我应该注意, short int check[10] = {1,1,1,1,1,1,1,1,1}; only 9 elements are 1, the last element will be initialized to 0, so this check will always be false , if you omit the size i.e. check[] = {1,1,1... you won't have this problem because the size of the array will be deduced by the number of elements in the initializer.只有 9 个元素为 1,最后一个元素将被初始化为 0,因此此检查将始终为false ,如果您省略大小,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现场演示

If you do not like if statements then try this:如果你不喜欢 if 语句,那么试试这个:

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

No need to use extra local storage, just loop until you see an element that is not the same.无需使用额外的本地存储,只需循环直到看到不一样的元素。 If you reach the end, everything is fine.如果你到达终点,一切都很好。 Otherwise not.否则不行。

See here: https://godbolt.org/z/8r6YK6W34见这里: https://godbolt.org/z/8r6YK6W34

Just for completeness here's a recursive version (no explicit if s):为了完整起见,这里有一个递归版本(没有明确的if s):

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

Here is a quick and dirty if -less implementation assuming two's complement without padding bits:这是一个快速而肮脏的if -less 实现,假设没有填充位的二进制补码:

#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));
}

You can generalize this method to check if the array contains a repeating sequence of length r :您可以推广此方法来检查数组是否包含长度为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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM