std::vector<class *> 无法正确构建副本

std::vector<Class *> does not get copy constructed correctly

本文关键字:构建 副本 vector lt class std gt      更新时间:2023-10-16

我有一个像这样的class粒子

class Particle
{
public:
    std::vector<Particle*> getNbh () const;
    void setNbh (const std::vector<Particle*>&);
private:
    std::vector<Particle*> nbh_;
};

Particle::setNbh(const std::vector<Particle*>&)功能的实现,

void Particle::setNbh (const std::vector<Particle*>& nbh)
{
    nbh_ = nbh;
}

则有一个非成员函数updateNeighbors (std::vector<Particle>& particles, double cutoff)

void updateNeighbors (std::vector<Particle>& particles, double cutoff)
{
    for (auto particle : particles)
    {
        auto nbh = std::vector<Particle*>();
        for (auto other : particles)
            if (&particle != &other 
                && norm(particle.getPosition() - other.getPosition()) < cutoff)
                nbh.push_back(&other);
        particle.setNbh(nbh);
    }
}

问题是,当我用这个函数更新邻居时,nbh_成员没有得到正确的更新,我测试它为每个粒子打印getNbh()的大小。

这是复制构造std::vector<Particle*>的正确方式,所以我可以得到所需的行为?

将两个循环中的for ( auto替换为for ( auto&&

您正在从particles向量创建每个Particle的本地副本,我强烈希望您不打算这样做。

auto&&在类型推导上下文中使用&&,这意味着auto&&要么是右值引用,要么是const引用,要么是普通引用,这取决于变量初始化的对象。当您不想考虑它时,这是一种不错的"默认"方法来遍历容器。

In

particle.setNbh(nbh);

您实际上是在迭代时将nbh(..)设置为元素的"副本"。如果您打算修改引用,则应该在迭代时使用引用。用途:

for (auto& particle : particles)