在为基于范围的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优化之后)?选择是否取决于vector的数据类型,还是取决于我们在循环内部执行的操作。PS:循环内的
cout
仅用于演示。
最佳答案
预期它们都不会表现得更快或更慢。您必须采取措施才能在您的特定平台上找到答案。或阅读汇编代码,您可能会发现其中的一部分或全部是相同的(可以在此处尝试:https://godbolt.org/)。
顺便说一句,如果您的循环体实际上在每次迭代中都写入cout
,则使用哪种循环样式都没有关系,因为cout
很慢并且 vector 中的整数迭代很快。
关于c++ - 基于范围的for循环的range_declaration中各个说明符之间的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62497276/