[英]how accurate is find() and distance()
我想我在返回迭代器位置时读到了distance()
可能很挑剔。 有时它不能返回正确的位置。 我想知道这是真的还是我没有正确使用它。
我试图找到何时将21的向量中的粒子悬停。 这个想法是,一旦有人悬停,就切换其他人的状态。
我正在使用find()
来知道粒子何时悬停,因此是正确的。
vector<bool>::iterator it;
it = find(_tmp->isParticleHovered.begin(), _tmp->isParticleHovered.end(), true);
if (it != _tmp->isParticleHovered.end()){// we look if a particle is being hovered.
isHovered = true;// we use this to check internally the first boid
}else{
isHovered = false;
}
现在,我不仅想知道它何时悬停,还想知道哪一个悬停了,所以我添加了以下内容:
vector<bool>::iterator it;
it = find(_tmp->isParticleHovered.begin(), _tmp->isParticleHovered.end(), true);
if (it != _tmp->isParticleHovered.end()){// we look if a particle is being hovered.
l = distance(_tmp->isParticleHovered.begin(), it);
isHovered = true;// we use this to check internally the first boid
}else{
isHovered = false;
l = -1;
}
因此,了解索引后,我想切换其他索引的状态,因此我想到了以下内容:
if ( l == -1){
if ( boidState5){
resetFamilyBoidState(_tmp);// makes all the particles go back to the same state
boidState2 = true;
boidState5 = false;
}
}else if ( l != -1){
if ( boidState2 ){
makeBoidStateless(_tmp, l);// I pass L, to this function, tell the function to switch all the particles to a different state except the one that is being hovered.
boidState5 = true;
boidState2 = false;
}
}
它会工作几次,但是当我快速从一个粒子悬停到另一个粒子时,它会感到困惑,有时l
会返回21,这将使其崩溃,因为粒子向量的大小为21-是最新的容器20。
我想出了一个既不使用find()
也不使用distance()
的解决方案:
int FamiliesController::returnInfoBoxState(){
for ( int i = 0; i < boidList.size(); i++){
if ( boidList[i]->boidState == 2){
return i;
}
}
return -1;
}
在控制器类中,我创建了一个函数,该函数将在调用该特定状态时返回索引号,否则将返回-1。 使用相同的if语句可以正常工作。
我很好奇地发现find()
和distance()
。 任何澄清都非常感谢。
std::distance
是精确的。 毫无疑问。
但是,您很可能会误解其功能。 您说它可能会返回“错误位置”。 它永远不会返回位置。 迭代器是一个位置。
另外,您可能需要检查std::bitset<21>
。 当位数固定时,它更合适,并且具有额外的辅助函数,例如.reset()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.