更高效的 STL(类似 STL)执行操作的方式,
是否有一种更类似于STL/更有效的方法来执行以下操作
for (int i=0 ; i< N ; ++i)
{
mystruct[i].key = myfunction(xp[i], yp[i], zp[i]);
mystruct[i].index = i;
}
,其中 mystruct 的类型为
struct KeyIndex
{
int key;
int index;
};
xp、yp 、 zp 是三个大小为 N 的浮点数组
double xp[N];
double yp[N];
double zp[N];
,而 myfunction 是具有签名 int myfunction 的某个函数(int, int ,int)
如果我需要将函数 myfunction
更改为函子以用于 STL 目的,那是可以的。
Is there a more STL like/efficient way of doing the following
for (int i=0 ; i< N ; ++i)
{
mystruct[i].key = myfunction(xp[i], yp[i], zp[i]);
mystruct[i].index = i;
}
where mystruct is of type
struct KeyIndex
{
int key;
int index;
};
xp, yp , zp are three floating point arrays of size N
double xp[N];
double yp[N];
double zp[N];
and myfunction is some function having signature int myfunction (int, int ,int)
If it is required for me to change the function myfunction
into a functor for STL purposes that is ok.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
但它肯定不会更快,而且毫无理由地更加晦涩难懂。正如评论中所述,这是简单
for
循环更好的情况之一。You can do:
But it surely isn't faster, and it's way more obscure for no good reason. As stated in the comment, this is one of the cases where a simple
for
loop is way better.数据或
myfunction
函数中是否有任何结构可以让您计算N
键值,而无需实际评估mufunction
N 次?
假设您有一个函数
sum(n)
,它计算数组arr
到索引n
的元素之和。如果您使用n
= 1234 调用它,则不需要使用n
= 1235 调用它,因为这会无缘无故地添加前 1234 个数字。在这种情况下,sum
(1235) =sum
(1234) +arr
[1234],计算速度要快得多。另一个优化是如果您的 (xp, yp, zp) 参数在数组中出现多次。在这种情况下,您将不必要地使用相同的参数多次调用
myfunction
,希望生成相同的结果。如果是这样,并且数据数组很大,但包含一组小得多的不同值,您可以将结果存储在某种缓存中。在调用 myfunction 之前,您检查缓存以查看是否尚未计算结果。如果您这样做了,请使用缓存的值;如果您没有这样做,请计算并将其添加到缓存中。
否则,您将不会以任何有意义的方式对其进行优化,而应该致力于使其尽可能具有可读性。
Is there any structure in the data or in the
myfunction
function that may allow you to calculate theN
key values without actually evaluatingmufunction
N
times?Say, you have a function
sum(n)
which calculates the sum of the elements of an arrayarr
up to indexn
. If you call it withn
= 1234 then you don't need to call it forn
= 1235 because that would add the first 1234 numbers for no reason. In this casesum
(1235) =sum
(1234) +arr
[1234], much faster to calculate.Another optimization would be if your (xp, yp, zp) parameters appear multiple times in the arrays. In that case you would unnecessarily call
myfunction
a large number of times with the same parameters, hopefully generating the same results.If this is so and the data arrays are large but contain a far smaller set of distinct values you can memoize the results in a cache of sorts. Before calling myfunction you check the cache to see if you haven't already calculated the results. Use the cached value if you did or calculate and add it to the cache if you didn't.
Otherwise you are not going to optimize that in any meaningful way and you should instead aim to make it as readable as possible.