使用指针访问 QVector 的元素
我在处理双打的指针和引用时遇到了麻烦。
我想通过名称访问 QVector 中的元素。该向量包含双精度数:
QVector<double> properties;
properties.append(28.0);
properties.append(1.0);
properties.append(44.0);
properties.append(0.001);
现在我创建指向双精度数的指针:
double* Amplitude;
double* Frequency;
double* PhaseDifference;
double* Stepsize;
这些指针应该提供对向量元素的访问:
Amplitude = &properties[0];
Frequency = &properties[1];
PhaseDifference = &properties[2];
Stepsize = &properties[3];
在我看来,取消引用这些指针应该给我正确的值,但事实并非如此。在这种情况下,我的前两个指针为零,第三个和第四个指针是正确的。
我尝试在向量中使用更多条目,结果是只有最后两个具有正确的值。那里出了什么问题?
我在构造函数中创建并打印值。向量的打印给出了正确的值!
有人有想法吗?
I have trouble with pointers and references to doubles.
I want to access elements in QVector by names. The vector contains doubles:
QVector<double> properties;
properties.append(28.0);
properties.append(1.0);
properties.append(44.0);
properties.append(0.001);
Now I create pointers to doubles:
double* Amplitude;
double* Frequency;
double* PhaseDifference;
double* Stepsize;
These pointers should provide access to the elements of my vector:
Amplitude = &properties[0];
Frequency = &properties[1];
PhaseDifference = &properties[2];
Stepsize = &properties[3];
In my opinion dereferencing these pointers should give me the correct values, but it doesn't. In this case I got zeros for the first two pointers and the third and fourth were correct.
I tried to use more entries in the vector and the result was that only the last two had the correct values. What is going wrong there?
I create and print the values in the constructor. Printing of the vector gives the right values!
Does anybody have an idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的命名指针实际上是迭代器。迭代器可能会失效。例如,每当您调整向量大小或向其中插入任何内容等时,请查找特定向量类型(在本例中为
QVector
)的迭代器失效的确切规则,并查看您是否已执行任何在打印之前使操作无效的迭代器。顺便说一句,取消引用无效的迭代器可能会导致未定义的行为。Your named pointers are in fact iterators. Iterators can be invalidated. For example, whenever you resize the vector, or insert anything into them, etc. Look up the exact rules of iterator invalidation for your particular vector type, in this case,
QVector
and see if you've performed any of those iterator invalidating operations prior to printing. Incidentally, dereferencing an invalidated iterator may result in undefined behavior.你一定做错了什么。这是有效的:
出现问题的原因是:
You must be doing something wrong. This works:
Reasons for things going wrong are:
您应该在初始化向量时设置向量的大小。一切都会好起来的,直到你改变它们(push/pop)之后,你的指针中的值将是未定义的。
You should set size of vector when you initialize them. Everything will be fine until you change them (push/pop) after that values in ur pointers will be undefined.
您的指针有可能在您获得它们的时间和您实际使用它们的时间之间已经失效。
如果调整 QArray 的大小(通过添加比当前可容纳的元素更多的元素),就会发生这种情况。
There is a possibility that your pointers may have been invalidated between the time you've obtained them, and the time you've actually used them.
This can happen if the
QArray
is resized (by adding more elements than it can currently accommodate).