【问题标题】:How to add an object from the first vector of pointer to second vector of pointer? C++如何将对象从指针的第一个向量添加到指针的第二个向量? C++
【发布时间】: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


【解决方案1】:

您可能需要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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    相关资源
    最近更新 更多