5

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;
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91

4 Answers4

9

In c++11 (or Boost Algorithm)

std::all_of(vecSamples.begin()+1,vecSamples.end(),
          [&](const T & r) {return r==vecSamples.front();})
sbabbi
  • 11,070
  • 2
  • 29
  • 57
  • I'm aware of the fact that OP is asking about a *non-empty* vector. Even so, I think that adding `!vecSamples.empty() ||` to your expression before the call to `std::all_of()` wouldn't damage your answer. What do you think? – JFMR Jan 27 '19 at 08:57
  • Simply replacing the `vecSamples.begin()+1` with just `vecSamples.begin()` in your call to `std::all_of()` also makes your code suitable for working with empty vectors, since the predicate won't be evaluated on an empty vector. – JFMR Jan 27 '19 at 09:03
4

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.

Ed Rowlett-Barbu
  • 1,611
  • 10
  • 27
2

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.

john
  • 7,897
  • 29
  • 27
1

If your vector contains at least one element:

std::equal(vecSamples.begin() + 1, vecSamples.end(), vecSamples.begin())
Daniel Laügt
  • 1,097
  • 1
  • 12
  • 17