简体   繁体   中英

C++ how to check if an element of all objects stored in a vector have the same value?

For example I have an vector of objects and they all have attribute PointX so I want to check if all of them have the same value of PointX and if they have it should return true or false whatever.

So in a kind of pseudo-code:

IF ( Object[1].getPointX() == Object[2].getPoint(x) == Object[3].getPoint(x) ){
      return true;
      }

The problem is that I have more than 55 objects so there has to be a way to compare them without writting them all individually. I know there must be with a for loop but still I have no idea.

thanks in advance.

edit: @awesomeyi your suggestion seems the easiest and more adequate to my needs (I'm not saying the others are not but I think they are too complicated for a newb like me) but it's not working, even if Xpoints are all the same or different it always returns false. here's what i have:

bool allKilled(){ 
auto checkpointx = Invader[0].getIfActive(); 
for(int i = 0; i < 55; ++i){ 
if(Invader[i].getIfActive() != checkpointx){
 return false;}
}
}

the getIfActive() just returns if its true or false, and i want this method to return true if all Active (attribute of the object) of all objects are all false.

Something like this:

auto refx = Object[0].getPointX();
bool b = std::all_of(Object.begin(),
                     Object.end(),
                     [refx](TheTypeOfTHeElements& e) 
                     { return e.getPointX() == ref; });

Obviously you need to check that Objects is not empty.

For loop?

auto checkpointx = Object[0].getPointX();
for(int i = 1; i < Object.size(); ++i){
    if(Object[i].getPointX() != checkpointx)
        return false;
}

I'd do it something like this:

template<typename Objects, typename Comparison>
bool is_all_same( Objects&& objects, Comparison&& comp ) {
  using std::begin; using std::end;
  auto&& b = begin(objects);
  auto&& e = end(objects);
  if (b == e)
    return true;
  auto&& first = *b;
  for( auto&& cur = std::next(first); cur != e; ++cur ) {
    if (!comp( first, cur ))
      return false;
  }
  return true;
}

use:

bool all_same_x = is_all_same( objs, []( Obj const& left, Obj const& right )->bool {
  return left.getPointX() == right.getPointX();
});

where objs is some container or range containing objects of type Obj .

The above code should work on all standard containers, C style arrays, custom containers that support the new for loops, and is close to optimal performance wise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM