C++ range based for loop, is the container copied? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-29 06:37:53

问题


In C++, it is allowed to iterate over every element of a container (let's take a vector for instance), like in

vector<CustomObject> container;
//push back some objects in container

for(CustomObject obj : container){
    //process obj
}

I have a question about the "for" behavior: is container copied to be used in the for or accessed by reference?


回答1:


The container is not being copied. It's being accessed by reference. However, the CustomObject is being copied for each loop. The compiler may optimize away the copy, but that is not guaranteed.

To prevent the copying of CustomObjectin this example, you'd do this: for(CustomObject& obj : container)




回答2:


The container is not copied. However, every element within it is copied. You can change this by specifying it using the ampersand. That is:

for (CustomObject &obj : container) {
     // Process obj
}

Usually the best decision when dealing with large containers.



来源:https://stackoverflow.com/questions/51387535/c-range-based-for-loop-is-the-container-copied

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!