从Vector内部的结构中获取浮点值

Getting float value from struct that is inside a Vector

本文关键字:获取 结构 Vector 内部      更新时间:2023-10-16

我有一个存储4个浮点的结构体Points。然后将这些结构放入向量中,因为我正在存储图形的点(也使用OpenGL)。

typedef struct {
    float x1, y1;                                                           
    float x2, y2;                                                           
} Points;
vector<Points> line;  
Points segment; 

我现在有一个函数,其中我的两个向量是自变量,我希望能够访问每个结构点(x1,x2,y1,y2)

int CyrusBeckClip (vector<Points>& line, vector<Points>& polygon) {
    // How can I access each segment.x1 in the vector? 
    // (I reuse the segment instance for each line drawn)
    return 0;
}

如何访问矢量中的每个segment.x1?

我希望我在这里很清楚,并提供了足够的信息。我尝试过输出&line.front();,但似乎不起作用。

for (Points& segment: line) {
    // here we can use segment.x1 and others
}
for (Points& segment: polygon) {
    // here we can use segment.x1 and others
}

这被称为基于范围的for循环。

您可以这样做:

// using an index
line[0].x1;
// using an iterator
std::vector<Points>::iterator = line.begin();
line_iter->x1; // access first element's x1
(*line_iter).x1 // access first element's x1
 // using front
 line.front().x1  // access first element's x1