【发布时间】:2017-11-28 16:33:57
【问题描述】:
这样声明对象的向量...
std::vector< std::shared_ptr<Boid> >m_flock;
std::vector< std::shared_ptr<Boid> >m_flock2;
这就是我在循环中创建对象的方式
//Create objects in first container
m_flock.resize(2);
for(auto &boid : m_flock)
{
boid = std::shared_ptr<Boid>(new Boid);
boid->setPos(20);
std::cout<< boid->getPos() <<std::endl;
}
//Create objects in second container
m_flock2.resize(3);
int num = 0;
for(auto &boid2 : m_flock2)
{
num +=10;
boid2 = std::shared_ptr<Boid>(new Boid);
boid2->setPos(num);
std::cout<< boid2->getPos() <<std::endl;
}
这是我需要帮助的主要部分。如何正确比较第一个容器中的对象和第二个容器中的对象的值?
// Compare 2 objects function from one container to another
// If it's 2nd object container's value is equals to the value of the first container,
// Then add this to the first container.
// And erase that specific element in the 2nd container
int i=0;
for(auto &boid : m_flock) //Container 1
{
for(auto &boid2 : m_flock2) //Container 2
{
//If they are the same position, then push_back to container 1.
if( boid2->getPos() == boid->getPos() )
{
//Push object of 2nd container to 1st container
m_flock.push_back(boid2);
//Delete the object that was being pushed into the 1st container.
m_flock2.erase(m_flock2.begin()+i); //Also is this the best way to delete that specic object?
++i;
}
}
}
所以现在当我遇到问题时会出现分段错误。有人可以给我建议吗?谢谢。
【问题讨论】:
-
m_flock2.erase(m_flock2.begin()+i)看起来很糟糕。真的有要删除的元素吗? -
您不应该在迭代容器时修改容器。您的程序表现出未定义的行为。
标签: c++ templates pointers stl smart-pointers