c++ - Would Iterator loop call end() for many times? -
#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); (auto = range.begin(); != range.end(); ++it) { // line std::cout << - range.begin() << "\n"; // line b } }
suppose use optimization (like g++ -ofast
).
in line a, program call range.end()
many times, instead of saving value of range.end() , compare value in every iteration of loop?
in line b, program call range.begin()
many times, instead of saving value of range.begin()
whole loop , subtract value in every iteration of loop?
in code, optimizer can see implementations of begin()
, end()
. can inline them, , hoist invariants out of loop.
the answer different if begin()
, end()
in different translation unit main()
, link-time late such optimizations.
Comments
Post a Comment