C++ - 在 STL vector 中操作对象?

标签 c++ memory pointers stl vector

我有这样的结构:

struct Rz3DContourNode {
  float x;
  float y;
  float z;
  float nx;
  float ny;
  float nz;
};

然后我将元素存储在 STL vector 中,如下所示:

 std::vector < Rz3DContourNode >  nodes;

现在我想更改 vector 中节点的 nx,ny 分量。我尝试如下:

*(&nodes[i].nx)=newNXValue;
*(&nodes[i].ny)=newNYValue;
*(&nodes[i].nz)=newNZValue;

这没有用。是因为 nodes[i] 返回了对象的拷贝吗?

有什么解决方案可以解决这个问题吗?

我不能使用指针 (Rz3DContourNode*) ,因为我在 OpenGL 中使用这个 vector 作为

glNormalPointer(GL_FLOAT,sizeof(Rz3DContourNode), &nodes[0].nx);

编辑 - 对不起。我实际上保留了一个 QList 并每次都获取 std::vector。这就是原因

std::vector<Rz3DContourNode> nodeVector = nodes.toVector().toStdVector();

最佳答案

为什么要为指针烦恼? [] 运算符返回对存储对象的引用,因此您可以这样做

nodes[i].nx = newNXValue;
nodes[i].ny = newNYValue;
nodes[i].nz = newNZValue;

关于C++ - 在 STL vector 中操作对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7305629/

相关文章:

c++ - 无法将 ncurses 与 Qt 链接

memory - 编程时保留 STM32F4 内存

ios - 呈现缓存的 View Controller 时 Swift 应用程序崩溃

pointers - 不兼容的指针类型添加了系统调用xv6-使用在sysfunc.h中定义的一致返回类型

c - 左值无效,函数指针也无效,这有什么用?调用函数就简单多了

c++ - 如何将 float 转换为字符串

c++ - 使用 c/c++ 宏禁用多行语句

c++ - 为什么我的模板元代码比 for 循环慢?

c++ - 是否可以返回对 std::vector 中数据的引用,并在 vector 超出范围后保留该引用?

c++ - 设备类中的设备指针 (Cuda C++)