std::vector<class *> 无法正确构建副本
std::vector<Class *> does not get copy constructed correctly
我有一个像这样的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)
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 无法在 CLion 中构建 C++ 项目
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用ndk-build.cmd构建Android.so文件
- libssh 的函数在构建 libssh 时无法在 Qt 和 cmake 错误中找到
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 用callgrind追踪不必要的副本
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 构建一个由C和C++文件组成的库
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- llvm构建器向基本块添加终止符
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- 为什么构建目录中新构建的共享库与安装目录中的副本具有不同的依赖项集?
- ifstream的已删除副本构建器的替代方法
- 我可以使用针对2008 VS运行时的构建与VS 2010,而没有VS 2008的副本吗
- std::vector<class *> 无法正确构建副本
- 在构建复合对象时消除不必要的副本