c++algorithmvectorcomparisonunique

Checking if all elements of a vector are equal in C++


If I have a vector of values and want to check that they are all the same, what is the best way to do this in C++ efficiently? If I were programming in some other language like R one way my minds jumps to is to return only the unique elements of the container and then if the length of the unique elements is more than 1, I know all the elements cannot be the same. In C++ this can be done like this:

//build an int vector
std::sort(myvector.begin(), myvector.end());
std::vector<int>::iterator it;
//Use unique algorithm to get the unique values.
it = std::unique(myvector.begin(), myvector.end());
positions.resize(std::distance(myvector.begin(),it));
if (myvector.size() > 1) {
    std::cout << "All elements are not the same!" << std::endl;
}

However reading on the internet and SO, I see other answers such using a set or the find_if algorithm. So what is the most efficient way of doing this and why? I imagine mine is not the best way since it involves sorting every element and then a resizing of the vector - but maybe I'm wrong.


Solution

  • You don't need to use std::sort. It can be done in a simpler way with std::adjacent_find:

    if ( std::adjacent_find( myvector.begin(), myvector.end(), std::not_equal_to<>() ) == myvector.end() )
    {
        std::cout << "All elements are equal each other" << std::endl;
    }
    

    Or, since C++20 with std::ranges::adjacent_find:

    if ( std::ranges::adjacent_find( myvector, std::ranges::not_equal_to() ) == myvector.end() )
    { /* ... */ }