c++ - 从自定义结构数组中提取数据
问题描述
我正在尝试制作一组粒子并为每个粒子分配一个从随机正态分布中挑选的 x、y 和 z 坐标。我想看看我得到了什么位置,并决定显示我的 x 坐标。这基本上就是我正在做的事情:
#include <omp.h>
#include <time.h>
#include <iostream>
#include <cmath>
#include <random>
using namespace std;
struct PARTICLE {
public:
double x;
double y;
double z;
PARTICLE() { } };
int main() {
//set up cluster of particles
int numberOfParticles = 10;
std::random_device rd{};
std::mt19937 gen{rd()};
std::normal_distribution<> d{0,1};
PARTICLE *clusterOfParticles [numberOfParticles];
for (int ind=0; ind<numberOfParticles; ind++){
cout<<"test"<<endl;
clusterOfParticles[ind]->x = d(gen);
cout<<clusterOfParticles[ind]->x<<endl; }
return 0;
}
我没有收到任何错误消息,并且可以看到正在显示“测试”。但我没有看到我的 x 坐标。它们甚至被存储在内存中吗?我哪里错了?
解决方案
您问题下方的评论基本上已经给出了答案。您的指针数组指向任何地方。
而且您使用的是 C99 样式可变长度数组 (VLA)。这在 C++ 中是不允许的。
我不想,但无论如何我都会用指针向你展示解决方案。采用:
PARTICLE *clusterOfParticles = new PARTICLE [numberOfParticles];
// Your code
delete [] clusterOfParticles;
但我不想那样做。相反,我说:
以后永远不要使用 C 样式数组。没有必要。
不要使用指针。永远不要使用原始指针。忘记上面的例子。至少使用 std::unique_ptr。
将您的代码修改为
// We will use a vector
std::vector<PARTICLE> clusterOfParticles(numberOfParticles);
for (int ind=0; ind<numberOfParticles; ind++){
cout<<"test"<<endl;
clusterOfParticles[ind].x = d(gen);
cout<<clusterOfParticles[ind].x<<endl; }
更简单,更不容易出错。
推荐阅读
- c# - 如何使用 EPPlus 在公式中获取超链接
- reactjs - 在反应返回语句中调用函数的方法
- android - 为 Facebook screenshot-tests-for-android 设置 gradle 插件的问题
- css - 调整窗口大小时 CSS 滚动捕捉是否总是中断?
- machine-learning - 将逻辑回归模型拟合到 MNIST 数据需要很长时间
- python - 如何将节点放置在特定位置 - networkx
- c# - Xero 会计发票对象未设置为参考
- javascript - 如何用函数链中的空字符串替换数据库中的空值
- scala - 在 scala 中,为什么 Range.hashCode() 这么慢并且不能更快?
- algorithm - 给定二维坐标系中的一组点,如果我们只访问所有点一次,如何计算最小距离和路径?