本文介绍了在循环中使用string.length()有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,假设string s
是这样:
for(int x = 0; x < s.length(); x++)
比这更好吗?:
int length = s.length();
for(int x = 0; x < length; x++)
谢谢,乔尔
推荐答案
通常,如果结果在迭代过程中没有改变,则应避免在循环的条件部分中调用函数.
In general, you should avoid function calls in the condition part of a loop, if the result does not change during the iteration.
因此,规范形式为:
for (std::size_t x = 0, length = s.length(); x != length; ++x);
请注意此处的三件事:
- 初始化可以初始化多个变量
- 条件用
!=
而不是<
表示 - 我使用前增量而不是后增量
- The initialization can initialize more than one variable
- The condition is expressed with
!=
rather than<
- I use pre-increment rather than post-increment
(我还更改了类型,因为负长度是无意义的,并且字符串接口是用std::string::size_type
定义的,在大多数实现中通常是std::size_t
.)
(I also changed the type because is a negative length is non-sense and the string interface is defined in term of std::string::size_type
, which is normally std::size_t
on most implementations).
尽管...我承认,性能并没有提高可读性:
Though... I admit that it's not as much for performance than for readability:
- 双重初始化意味着
x
和length
的作用域都尽可能严格 - 通过记住结果,读者不会怀疑长度在迭代过程中是否会发生变化
- 当您不需要使用旧"值创建临时目录时,使用预增量通常会更好.
- The double initialization means that both
x
andlength
scope is as tight as necessary - By memoizing the result the reader is not left in the doubt of whether or not the length may vary during iteration
- Using pre-increment is usually better when you do not need to create a temporary with the "old" value
简而言之:使用最好的工具完成手边的工作:)
In short: use the best tool for the job at hand :)
这篇关于在循环中使用string.length()有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!