以这种方式声明对象的向量...
wscript
这就是我在循环中创建对象的方式
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;
}
所以现在当我遇到问题时会出现分段错误。有人可以告诉我吗?谢谢。
答案 0 :(得分:0)
您可能需要std::partition
,或者,如果元素的顺序很重要,std::stable_partition
。像这样(未经测试):
auto middle = std::partition(m_flock2.begin(), m_flock2.end(),
[&](const std::shared_ptr<Boid>& boid2) {
return m_flock.end() == std::find_if(m_flock.begin(), m_flock.end(),
[&](const std::shared_ptr<Boid>& boid) {
return boid->getPos() == boid2->getPos();
});
});
// Now in m_flock2, elements between begin() and middle don't match any
// in m_flock, while elements between middle and end() all do.
// Move the second half over to the end of m_flock, then erase from m_flock2
m_flock.insert(m_flock.end(),
std::make_move_iterator(middle),
std::make_move_iterator(m_flock2.end()));
m_flock2.erase(middle, m_flock2.end());