缓存结束迭代器 - 好主意或坏主意? [英] Caching the end iterator - Good idea or Bad Idea?

查看:168
本文介绍了缓存结束迭代器 - 好主意或坏主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,为了效率和速度的目的,缓存一个结束迭代器(特别是STL容器)是个好主意?例如在下面的代码中:

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;
}

在什么条件下,结束值会失效?将从容器中清除原因结束在所有 STL容器中无效,或只是部分?

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?

推荐答案

向量的简单情况下, end 从容器中移除元件;虽然,通常最安全的假设如果你在迭代容器的同时对其进行变异,所有迭代器会变得无效。迭代器可以在任何给定的STL实现中以不同的方式实现。

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.

对于缓存 end 迭代器 - 有效的缓存它,但要找出它是否实际上是更快,在你的情况下,最好的赌注是你配置你的代码,看看。从向量中检索 end 迭代器可能是最近的STL库和编译器的快速实现, > have 在过去的缓存 end 迭代器的项目中工作,这给我们带来了显着的速度提升。 (这是在PlayStation 2上,所以带一粒盐)。

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.)

这篇关于缓存结束迭代器 - 好主意或坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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