动态分配数组

时间:2012-09-26 07:24:11

标签: c++

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

2 个答案:

答案 0 :(得分:6)

是的,改为使用std::vector

结合push_back,您可以动态增加元素数量。

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

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

coordinates[0], coordinates[1]...

答案 1 :(得分:0)

正如所建议的那样,std::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,但这种容器的插入并不昂贵所有(至少不像矢量那么贵)。

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