1

我正在开发一个 OpenGL/C++ 程序,当我在窗口中绘制坐标时,我需要在其中存储坐标。但由于绘制的点数未定义,我无法确定数组的大小。是否可以为数组动态分配空间?我可以使用任何其他数据结构来完成相同的任务吗?

4

2 回答 2

6

是的,使用 astd::vector代替。

结合push_back你可以动态增加元素的数量。

std::vector<Coordinate> coordinates;
coordinates.push_back(Coordinate(0,0));
coordinates.push_back(Coordinate(1,1));

您可以像访问数组一样访问元素:

coordinates[0], coordinates[1]...
于 2012-09-26T07:25:00.473 回答
0

如建议的那样, anstd::vector是一个不错的选择,并且此容器可确保连续内存,这对于将其作为坐标缓冲区传递很有用:

std::vector<Coordinate> coordinates;
coordinates.push_back(Coordinate(0,0));
coordinates.push_back(Coordinate(1,1));
// ... add more coordinates...

RenderBuffer(coordinates.data());

当然,只要内存适合缓冲区格式。

但是,由于使用连续内存,插入方法可能会由于内存块的重新分配而代价高昂;如果这可能是一个问题,如果您知道内存的最大/最小要求,您可以摆脱它保留一个大小:

// Create 100 instances of Coordinate and fill all instances with Coordinate(0, 0)
std::vector<Coordinate> coordinates(100, Coordinate(0, 0));

coordinates[0] = Coordinate(0,0);
coordinates[1] = Coordinate(1,1);
// ... add more coordinates...

RenderBuffer(coordinates.data());

但如果你这样做,使用数组没有区别:

// Create 100 instances of Coordinate and fill all instances with Coordinate(0, 0)
Coordinate[100];

coordinates[0] = Coordinate(0,0);
coordinates[1] = Coordinate(1,1);
// ... add more coordinates...

RenderBuffer(coordinates);

除了一个例外,如果需要,数组无法更改其大小,但std::vector可以调整大小:

// Create 100 instances of Coordinate and fill all instances with Coordinate(0, 0)
std::vector<Coordinate> coordinates(100, Coordinate(0, 0));

coordinates[0] = Coordinate(0,0);
coordinates[1] = Coordinate(1,1);
// ... add lots of lots of lots of coordinates...

// Damn! We need more Coordinates, let's add more without worrying about resizing:
coordinates.push_back(Coordinate(0,0));
coordinates.push_back(Coordinate(1,1));    

RenderBuffer(coordinates.data());

如果不需要连续内存,则必须考虑使用其他容器,如std::list,插入方法相同std::list<>::push_back,但这种容器的插入一点也不贵(至少不像vector那么贵)。

您也可以使用std::vector<>::resize一次调整大小的方法,而不是调整某些std::vector<>::push_back调用的大小。

于 2012-09-26T08:28:20.647 回答