C++: Fastest method to check if all array elements are equal

后端 未结 10 1995
庸人自扰
庸人自扰 2020-12-01 12:50

What is the fastest method to check if all elements of an array(preferable integer array) are equal. Till now I have been using the following code:

bool chec         


        
10条回答
  •  死守一世寂寞
    2020-12-01 13:10

    Here is a solid solution which is valid C++11. The advantages is that you do not need to manually play with the indexes or iterators. It is a best practice to

    prefer algorithm calls to handwritten loops [Herb Sutter - C++ Coding Standards]

    I think this will equally efficient as Paul R's solution.

    bool check(const int a[], int n)
    {
          return !std::all_of(a, a+n, [a](int x){ return x==a[0]; });
    }
    

提交回复
热议问题