在为基于范围的for -循环声明范围时,我见过许多类型的类型说明符,如:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (const int& i : v) // access by const reference
std::cout << i << ' ';
std::cout << '\n';
for (auto i : v) // access by value, the type of i is int
std::cout << i << ' ';
std::cout << '\n';
for (auto&& i : v) // access by forwarding reference, the type of i is int&
std::cout << i << ' ';
std::cout << '\n';
const auto& cv = v;
for (auto&& i : cv) // access by f-d reference, the type of i is const int&
std::cout << i << ' ';
std::cout << '\n';
}
// some aren't mentioned here, I just copied this snippet from cppreference在-O2或-O3优化之后,哪一个预期执行得更快?选择取决于向量的数据类型,还是取决于我们在循环中执行的操作。
PS:循环中的cout只是为了演示。
发布于 2020-06-21 10:41:59
他们中没有人被期望表现得更快或更慢。你必须通过测量才能在你的平台上找到答案。或者阅读程序集代码,您可能会发现它们中的一些或全部是相同的(您可以在这里尝试:https://godbolt.org/)。
另外,如果您的循环体实际上是在每次迭代中写入cout,那么使用哪种循环样式并不重要,因为cout速度慢,而且向量中的整数迭代速度很快。
https://stackoverflow.com/questions/62497276
复制相似问题