#include <vector>
#include <iostream>
class Range {
typedef typename std::vector<int> Vec;
typedef typename Vec::iterator Iterator;
public:
Range(Vec& vec, const int start_id, const int size)
: vec_{vec},
it_begin_{vec_.begin() + start_id},
it_end_ {vec_.begin() + start_id + size}
{}
Iterator& begin() {return it_begin_;}
Iterator& end() {return it_end_;}
private:
Vec& vec_;
Iterator it_begin_;
Iterator it_end_;
};
int main()
{
std::vector<int> a;
a.resize(100);
Range range(a,0,10);
for (auto it = range.begin(); it != range.end(); ++it) { // Line A
std::cout << it - range.begin() << "\n"; // Line B
}
}
假设我使用优化(如 g++ -Ofast
)。
在 A 行中,程序是否会多次调用 range.end()
,而不是保存 range.end() 的值并在循环的每次迭代中将该值与它进行比较?
在 B 行中,程序是否会多次调用 range.begin()
,而不是为整个循环保存 range.begin()
的值,并且然后在循环的每次迭代中从中减去该值?
最佳答案
在您的代码中,优化器可以看到 begin()
和 end()
的实现。它可以内联它们,并将不变量提升到循环之外。
如果 begin()
和 end()
与 main()
在不同的翻译单元中,答案可能会有所不同,因为链接时间对于此类优化来说通常为时已晚。
关于c++ - Iterator循环会多次调用end()吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40533339/