簡體   English   中英

如何檢查數組中的所有值是否相同?

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

假設我有一個數組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 ,但這非常不專業。
不妨知道,還有其他方法可以做到嗎?

正如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;
}

您可以像這樣調用 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完全沒問題,沒有什么不專業的。

我應該注意, short int check[10] = {1,1,1,1,1,1,1,1,1}; 只有 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");
}

現場演示

如果你不喜歡 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

為了完整起見,這里有一個遞歸版本(沒有明確的if s):

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

這是一個快速而骯臟的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));
}

您可以推廣此方法來檢查數組是否包含長度為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