简体   繁体   English

将迭代器传递给函数

[英]Passing iterator into function

I have the following code which is being used to find the weakest target out of a vector which is a vector containing a pointer to all the active units.我有以下代码用于从向量中找到最弱的目标,向量是一个包含指向所有活动单元的指针的向量。 I am trying to create an iterator that will go through each unit and pass it to another function called can_attack(Unit &u, Unit &v) which takes two units and measures if they are close enough to each other to attack.我正在尝试创建一个迭代器,它将遍历每个单元并将其传递给另一个名为 can_attack(Unit &u, Unit &v) 的函数,该函数采用两个单元并测量它们是否足够接近以进行攻击。

On compilation I am getting the following error "error: reference to type 'const Unit' could not bind to an lvalue of type 'Unit *const'".在编译时,我收到以下错误“错误:对类型 'const Unit' 的引用无法绑定到类型为 'Unit *const' 的左值”。 I understand that I am passing in the wrong type of variable but am unsure how to turn the iterator into a const Unit.我知道我传入了错误类型的变量,但不确定如何将迭代器转换为 const 单元。 Thanks for any help谢谢你的帮助

void World::enemies_within_attack_range(const Unit &u,
                                    vector<Unit*> &targets) const
{
  targets.clear();
  vector<Unit*>::const_iterator it=units.begin();
  for(it;it!=units.end();it++){
    if((*it)->team != u.team){
        if(can_attack(u,(*it))){
            targets.push_back(*it);
        }
     }
  }

}

The problem is in can_attack call and the parameter const Unit &u.问题在于 can_attack 调用和参数 const Unit &u。 The call has to be corrected as songyuanyao mentioned: can_attack(u,*(*it)).调用必须更正,因为songyuanyao提到:can_attack(u,*(*it))。 But this is not the only problem.但这并不是唯一的问题。 There are three options:共有三个选项:

  1. instead of const Unit &u, declare u as Unit & u;而不是 const Unit &u,将 u 声明为 Unit & u;
  2. instead of can_attack(Unit &u, Unit &v), declare it as can_attack(const Unit &u, Unit &v) if possible;如果可能,将其声明为 can_attack(const Unit &u, Unit &v) 而不是 can_attack(Unit &u, Unit &v);
  3. (this is probably the worst option) use call can_attack(const_cast < Unit& > (u),*(*it)). (这可能是最糟糕的选择)使用 call can_attack(const_cast < Unit& > (u),*(*it))。

The choice is yours.这是你的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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