如何在不迭代的情况下对数组中的每个元素调用方法

How to call a method to every element in an array without iterating through it?

本文关键字:元素 方法 调用 数组 迭代 情况下      更新时间:2023-10-16

我正在写一个小程序,其中有一个由25个点组成的数组。每个点都有自己的位置、大小和颜色,当我使用图形库(Allegro(时,我有一种在屏幕上打印它们的方法。

我需要同时打印它们,并使用:

for (int i = 0; i < m_size ; i++)
{
points[i].move();
points[i].draw();
}

一个接一个地打印。肯定效果更好的是:

for (int i = 0; i < m_size ; i++)
{
points[0].move();
points[0].draw();
points[1].move();
points[1].draw();
// ...
points[24].move();
points[24].draw();
}

当然,这远不是最佳解决方案;但效果非常好。问题是,有没有办法将第二个选项减少到更少的行数?

编辑:

void Particula::move(){
// Modifies private position attributes.
m_x += rand() % 50;
m_y += rand() % 50;
}
void Particula::draw(){
// Draws the point given its private attributes.
printf("Drawing circle... n");
// printf ("[ DEBUG:] X: %f, Y: %f, Radius: %f", m_x, m_y, m_radius);
al_draw_filled_circle(m_x, m_y, m_radius, m_color); // Draws the point.
al_flip_display(); // Updates the display.
}

预期结果是:

  1. 点一个接一个地出现
  2. 绘制完所有25个点后,清除显示
  3. 修改属性以设置新坐标
  4. 同时重新绘制所有点(或使其显示在屏幕上(
  5. 重复不同次数(可能是100或500次(

如果我理解正确,您的第二个代码块应该只执行一次,而不需要for循环。否则,您将一次又一次地打印这些点。

肯定效果更好的是。。。

根据这种理解,这"肯定"是错误的。您必须编写冗长且可能有错误的代码;它并不比for循环版本更优化——如果(它认为(解包更好的话,普通编译器会解包循环。(通常是正确的(因此,不需要手动拆包。

就我阅读Allegro文档而言,渲染似乎是基于类似位图的对象完成的。因此,您可以尝试先将点绘制到缓冲位图,类似

BITMAP *bmp = create_bitmap(320, 200); // make a bitmap in RAM
clear_bitmap(bmp); // zero the memory bitmap 
putpixel(bmp, x, y, color); // draw onto the memory bitmap 
blit(bmp, screen, 0, 0, 0, 0, 320, 200); // copy it to the screen 

但是对于每个点使用for循环。

请注意,这只是一个可能的结果的假设,因为我从未使用过快板。

代码复制自:http://www.allegro.free.fr/onlinedocs/en/index009.html

这样修改代码就成功了:

for(int i = 0; i < N; i++) // being N a variable number.
{
for (int h = 0; h < m_size; h++)
{
point[h].move();
point[h].draw();
}
al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));
al_rest(0.1);
}