转载自 c++ - What is the correct way of using C++11's range-based for? - Stack Overflow
考虑以下准则
如果只是要观察元素【不修改】,请使用:
-
for (const auto& elem : container) // capture by const reference
- 1 如果对象复制起来很便宜(如ints、doubles 等),则可以使用稍微简化的形式:
for (auto elem : container) // capture by value
- 1 如果对象复制起来很便宜(如ints、doubles 等),则可以使用稍微简化的形式:
- 如果想要修改元素,请使用:
for (auto& elem : container) // capture by (non-const) reference
- 1 如果容器使用“代理迭代器”(如std::vector<bool>),请使用:
for (auto&& elem : container) // capture by &&
- 1 如果容器使用“代理迭代器”(如std::vector<bool>),请使用: