如何在不迭代的情况下对数组中的每个元素调用方法
How to call a method to every element in an array without iterating through it?
我正在写一个小程序,其中有一个由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.
}
预期结果是:
- 点一个接一个地出现
- 绘制完所有25个点后,清除显示
- 修改属性以设置新坐标
- 同时重新绘制所有点(或使其显示在屏幕上(
- 重复不同次数(可能是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);
}
相关文章:
- 数组元素打印的递归方法
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 有什么方法可以将元素添加到列表中,如图所示?
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- C++将所有元素从矢量复制到地图/unordered_map的最佳方法
- 在C++中更改结构内部元素的方法?
- 通过作为指向 C++ 函数的指针传递来访问 std::array 元素的正确方法是什么?
- 有没有更快的方法可以在 std::vector 中插入元素
- 返回向量元素的 l 值的正确方法是什么?
- 按升序打印矢量的所有元素直到它为空而没有重复项的最有效方法是什么?
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 如何在不迭代的情况下对数组中的每个元素调用方法
- 是否有更有效的方法来检查元素是否在给定的区间内
- 这种获取模板参数包中最后一个元素的方法是否有隐藏的开销?
- 将__m256的奇怪元素提取到__m128中的有效(在锐龙上)方法?
- 为什么 memcpy() 是一种将元素添加到 'std::map' 的方法?
- 从长(且合理)稀疏向量中选择随机元素的最有效方法是什么?
- 如何使用返回第 n 个元素的方法创建元组
- 带有移除任何元素方法的c++堆
- 如何在带有input的map元素方法上使用std::for_each