为什么C ++ STL容器的开始和结束函数按值而不是按常量引用返回迭代器? [英] Why do C++ STL container begin and end functions return iterators by value rather than by constant reference?

查看:67
本文介绍了为什么C ++ STL容器的开始和结束函数按值而不是按常量引用返回迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我查看不同STL对象和函数的标准时,对我来说没有什么意义的是为什么容器对象的begin()和end()函数将按值而不是按常量返回迭代器参考?在我看来,迭代器可以由容器对象在内部保存,并在容器发生突变时进行调整.这样可以减少在这样的for循环中创建不必要的临时文件的成本:

As I look at the standard for different STL objects and functions, one thing that doesn't make sense to me is why would the begin() and end() functions for container objects return an iterator by value rather than by constant reference? It seems to me that iterators could be held by the container object internally and adjusted whenever the container is mutated. This would mitigate the cost of creating unnecessary temporaries in for loops like this:

for (std::vector<int>::iterator it=my_vec.begin(); it!=my_vec.end(); ++it){
    //do things
}

这是一个有效的问题吗?关于使用对迭代器的引用,这有什么不好的主意吗?是否大多数编译器实现都会优化这种担忧?

Is this a valid concern? Is there something about using references to iterators that makes this a bad idea? Do most compiler implementations optimize this concern away anyway?

推荐答案

迭代器被设计为轻量且可复制(可分配).例如,对于向量,迭代器实际上可能只是一个指针.此外,迭代器的全部目的是要从容器中解耦算法,因此容器根本不必关心其他任何人当前持有的迭代器类型

Iterators are designed to be light-weight and copyable (and assignable). For example, for a vector an iterator might literally just be a pointer. Moreover, the whole point of iterators is to decouple algorithms from containers, and so the container shouldn't have to care at all what kind of iterators anyone else is currently holding

这篇关于为什么C ++ STL容器的开始和结束函数按值而不是按常量引用返回迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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