c.h*_*hes 3 c++ optimization containers stl
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
}
Run Code Online (Sandbox Code Playgroud)
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?
迭代器被设计为轻量级和可复制(和可分配)。例如,对于向量,迭代器实际上可能只是一个指针。此外,迭代器的全部意义在于将算法与容器解耦,因此容器根本不必关心其他人当前持有什么样的迭代器
如果begin和end方法返回一个引用,容器将被迫将这些迭代器中的每一个作为成员。标准人员试图为实现留下尽可能多的灵活性。
例如,您可以为一个数组创建一个简单的包装器,它作为一个标准容器,不消耗任何额外的内存。如果需要这个包装器来包含迭代器,它就不再那么简单或那么小了。
| 归档时间: |
|
| 查看次数: |
1447 次 |
| 最近记录: |