Caching the end iterator - Good idea or Bad Idea?(缓存结束迭代器——好主意还是坏主意?)
问题描述
Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code:
std::vector<int> vint;
const std::vector<int>::const_iterator end = vint.end();
std::vector<int>::iterator it = vint.begin();
while (it != end)
{
....
++it;
}
Under what conditions would the end value be invalidated? would erasing from the container cause end to be invalidated in all STL containers or just some?
In the simple case of a vector
, the end
iterator will change when you add or remove elements from the container; though, it's usually safest to assume that if you mutate the container while iterating over it, all iterators to it become invalid. Iterators may be implemented differently in any given STL implementation.
With regard to caching the end
iterator -- it's certainly valid to cache it, but to find out if it is actually faster in your case, the best bet is for you to profile your code and see. While retrieving the end
iterator from a vector
is likely a fast implementation with a recent STL library and compiler, I have worked on past projects where caching the end
iterator gave us a significant speed boost. (This was on the PlayStation 2, so do take with a grain of salt.)
这篇关于缓存结束迭代器——好主意还是坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:缓存结束迭代器——好主意还是坏主意?
基础教程推荐
- 初始化变量和赋值运算符 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++ #define 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- C++定义类对象 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- C++按值调用 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- C语言访问数组元素 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23