C ++向量在/ []运算符速度 [英] C++ Vector at/[] operator speed

查看:131
本文介绍了C ++向量在/ []运算符速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了给函数选项修改向量我不能做

In order to give functions the option to modify the vector I can't do

curr = myvec.at( i );
doThis( curr );
doThat( curr );
doStuffWith( curr );

但我要做:

doThis( myvec.at( i ) );
doThat( myvec.at( i ) );
doStuffWith( myvec.at( i ) );

(我的另一个问题的答案指出)

(as the answers of my other question pointed out)


  • 然后我会打电话到 myvec.at()与第一个使用变量存储结果的示例相比,它有多快?

  • I'm going to make a hell lot of calls to myvec.at() then. How fast is it, compared to the first example using a variable to store the result?

我有不同的选择吗?

当它变得严重时,会有几千个调用 myvec.at()每秒。

When it's getting serious there will be thousands of calls to myvec.at() per second. So every little performance-eater is important.

推荐答案

您可以使用引用:

int &curr = myvec.at(i);
// do stuff with curr

位于成员函数执行边界检查以确保参数在向量的大小内。分析只是确切地知道与 operator [] 相比有多慢。在这里使用引用允许你做一次查找,然后在其他地方使用结果。如果你想保护自己免受意外更改的影响,你可以使用它来引用 - const

The at member function does bounds checking to make sure the argument is within the size of the vector. Profiling is only way to know exactly how much slower it is compared to operator[]. Using a reference here allows you to do the lookup once and then use the result in other places. And you can make it a reference-to-const if you want to protect yourself from accidentally changing the value.

这篇关于C ++向量在/ []运算符速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆