Neil Kirk
Neil Kirk

Reputation: 21813

Test if all elements of a vector are equal

I want to test if a non-empty vector contains identical elements. Is this the best way?

count(vecSamples.begin()+1, vecSamples.end(), vecSamples.front()) == vecSamples.size()-1;

Upvotes: 5

Views: 7362

Answers (4)

Daniel Laügt
Daniel Laügt

Reputation: 1147

If your vector contains at least one element:

std::equal(vecSamples.begin() + 1, vecSamples.end(), vecSamples.begin())

Upvotes: 1

Ed Barbu
Ed Barbu

Reputation: 1649

As @john correctly points out, your solution iterates over the entire container even if the first two elements are different, which is quite a waste.

How about a purely no-boost no c++11 required solution?

bool allAreEqual = 
  find_if(vecSamples.begin() + 1, 
    vecSamples.end(), 
    bind1st(not_equal_to<int>(), vecSamples.front())) == vecSamples.end();

Stops on first non-equal element found. Just make sure your vecSamples is non-empty before running this.

Upvotes: 4

sbabbi
sbabbi

Reputation: 11201

In c++11 (or Boost Algorithm)

std::all_of(vecSamples.begin()+1,vecSamples.end(),
          [&](const T & r) {return r==vecSamples.front();})

Upvotes: 9

john
john

Reputation: 8027

Probably not, because it always examines all the elements of the vector even if the first two elements are different. Personally I'd just write a for loop.

Upvotes: 2

Related Questions