c++ - 操作迭代器列表+指针

标签 c++ pointers iterator sfml

我正在尝试检查所有实体的所有碰撞。我这样做是这样的: 我的父类“实体”有一个 static std::list<Entity*> allEntities

所有子类的构造函数都有这句话Entity::AddEntity((*this));

我有一个属性(property)std::list< Entity*> m_collisionWith;它将获取具有交集的实体的所有指针

之后,我在实体类中有一个静态函数:

for (std::list<Entity*>::iterator it = allEntities.begin(); it != allEntities.end(); it++) //to check everything...
{

    for (std::list<Entity*>::iterator itSec = allEntities.begin(); itSec != allEntities.end(); itSec++) // ... with everything
    {

        if ((*it)->m_spriteCharacter[(*it)->m_currentFrameCharacter].getGlobalBounds().intersects((*itSec)->m_spriteCharacter[(*itSec)->m_currentFrameCharacter].getGlobalBounds()) && *itSec != (*it)) //to_check if we have an intersection between two objects
        {
            if ((*it)->m_collisionWith.empty())
            {   
                (*it)->m_collisionWith.push_back((*itSec));
            }
            else
            {
                for (std::list<Entity*>::iterator itThr = (*it)->m_collisionWith.begin(); itThr != (*it)->m_collisionWith.end(); itThr++)
                {
                    if ((*itThr) != (*itSec)) //to check if the second object is not here yet. itThr will be every objects in m_collisionWith
                    {           
                        (*it)->m_collisionWith.push_back((*itSec)); 
                    }

                }
            }
        }
    }
}

所以我想检查一个实体是否与另一个实体有交集,如果有,我不想将它添加到 m_collision 中。 通常,如果我有 3 个实体,m_collision.size() 等于 3,但它会不停地增长

最佳答案

for (std::list<Entity*>::iterator itThr = (*it)->m_collisionWith.begin(); itThr != (*it)->m_collisionWith.end(); itThr++)
{
     if ((*itThr) != (*itSec)) //to check if the second object is not here yet. itThr will be every objects in m_collisionWith
     {           
          (*it)->m_collisionWith.push_back((*itSec)); 
     }

}   

对于 (*i​​t)->m_collisionWith 中不等于 *itSec 的每个元素,这会将 itSec 推到后面。应该是:

bool exists = false;
for (std::list<Entity*>::iterator itThr = (*it)->m_collisionWith.begin(); itThr != (*it)->m_collisionWith.end(); itThr++)
{
     if ((*itThr) != (*itSec)) //to check if the second object is not here yet. itThr will be every objects in m_collisionWith
     {           
          exists = true;
          break;
     }

}
if (!exists) 
{
    (*it)->m_collisionWith.push_back((*itSec)); 
} 

关于c++ - 操作迭代器列表+指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32062272/

相关文章:

java - 使用迭代器从 ArrayList 中删除字符串数组

c++ - 基于上下文的 partition_copy

c++ - 模板和 typedef 错误

c++ - 甚至未被引用的类方法的未解析外部符号

c++ - 从哪里获取设备类型常量描述?

链表段错误的C++数组

java - 在java中使用ListIterator作为LinkedList时遇到问题

C++如何读取值以逗号分隔的文件

c - 这个函数有什么作用?

C 指向字符的指针