c++如何检查数组中的元素是否相等

C++ how to check if elements in an array are equal?

本文关键字:元素 是否 数组 何检查 检查 c++      更新时间:2023-10-16

我正试图编写一个程序,检查是否在一个数组中的所有值是相等的使用for循环,但我无法找出一种方法,如果语句检查数组中的每个值是否相等,而不是不断重复"if a[i] == a[1] && a[i] == a[0]"等。我不想这样做,因为我想让它适用于任何大小的数组。任何帮助都非常感激!

    for (unsigned i = 0; i < val; i++){
       if (a[i] == a[0])
          return true;
       else
          return false;
    }
for (unsigned i = 0; i < val; i++) {
    if (a[i] != a[0]) {
        return false;
    }
}
return true;

应该可以了。

在这种情况下,代码将在不匹配的值上立即失败。然而,对于匹配的值,它只是继续检查(我们知道我们需要测试数组的每个元素,无论如何)。一旦完成,它就知道一切正常(因为我们没有提前返回),并返回true。

#include <algorithm>
#include <vector>
#include <iostream>
int main(int argc, char** argv)
{
    std::vector<int> eq{ 1, 1, 1, 1 };
    std::vector<int> nq{ 1, 2, 1, 1 };
    bool eq_res = std::all_of(std::begin(eq), std::end(eq),
        [&eq](int c) -> bool
    {
        return eq[0] == c;
    });
    bool nq_res = std::all_of(std::begin(nq), std::end(nq),
        [&nq](int c) -> bool
    {
        return nq[0] == c;
    });
    std::cout << "eq: " << eq_res << std::endl;
    std::cout << "nq: " << nq_res << std::endl;
}

编制c++——std=c++11 main.cpp

只是为了好玩,使用lambda表达式

#include <algorithm>
using namespace std;
template<size_t N>
bool func(int (&arr)[N])
{
    int* pOddValue = std::find_if(begin(arr), end(arr), 
        [&] (int val){ return val != arr[0];});
    return pOddValue != end(arr);
}

使用分治法,当n = 2^k时,我们可以像这样将比较次数减少到n-1:

bool divide(int arr[],int size)
{
    if( size == 2 ) return arr[0] == arr[1];
    if( divide(arr,size/2) && divide(arr+size/2,size/2) )
        return arr[0] == arr[size/2];
    return false;
}

另一种类似的方法:

for (unsigned i = 1; i < val; i++) {
    if (a[i] != a[i-1]) {
        return false;
    }
}
return true;

似乎不需要处理val = 0。你可以在一行内完成。

#include <functional>
#include <algorithm>
using namespace std;
return all_of(
    a+1, a+val,
    bind(equal_to<remove_pointer<decltype(a)>::type>(), a[0], placeholders::_1));