[英]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. 例如,我有一个对象向量,它们都具有PointX属性,因此我想检查它们是否都具有相同的PointX值,以及是否具有返回的true或false。
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. 问题是我有55个以上的对象,因此必须有一种比较它们的方法,而不必单独编写它们。 I know there must be with a for loop but still I have no idea.
我知道必须有一个for循环,但我仍然不知道。
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. 编辑:@awesomeyi,您的建议似乎最容易满足我的需求(我不是说其他人不是,但我认为对于像我这样的新手来说它们太复杂了),但是即使Xpoints都一样,它也不起作用或不同,它总是返回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. 如果所有对象的所有Active(对象的属性)都为false,则getIfActive()仅返回其true或false,并且我希望此方法返回true。
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. 显然,您需要检查
Objects
是否为空。
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
. 其中
objs
是一些包含Obj
类型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. 上面的代码应该在所有支持新的for循环的标准容器,C样式数组,自定义容器上工作,并且接近最佳性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.