1

How many times would myVector.cend() be called at runtime:

    std::vector<int> myVector;

        // ...

    for (auto it = myVector.cbegin(); it != myVector.cend(); ++it)
    {
       // ...
    }

It should be called either once or myVector.size() + 1 times, but I'm not sure how much we can expect the compiler to optimize things here. Because of that, I almost always add beforehand:

const auto end = myVector.cend();

and fix the loop this way:

for (auto it = myVector.cbegin(); it != end; ++it)
Barry
  • 286,269
  • 29
  • 621
  • 977
Pippin
  • 323
  • 1
  • 9
  • 6
    Use a [range based for loop](http://en.cppreference.com/w/cpp/language/range-for) and then you know it is only called once. – NathanOliver Aug 10 '16 at 20:09
  • 5
    Do it in the simpler way to read, until your profiler tells you that it needs to change. – GManNickG Aug 10 '16 at 20:11
  • Yes I'm aware of range based for loops. I agree that my example is poor, but I would still be interested in the answers. – Pippin Aug 10 '16 at 20:12
  • Why do you think cend() is more expensive than a variable load? – stark Aug 10 '16 at 20:14
  • Your code guarantees that cend() will be called one more times than necessary. – stark Aug 10 '16 at 20:15
  • 3
    If you *really* want to know what the compiler does, then inspect the generated asm. – Jesper Juhl Aug 10 '16 at 20:18
  • @JesperJuhl ....for every *possible* implementation? – Kyle Strand Aug 10 '16 at 20:20
  • 1
    @Kyle Strand possibly. Depending on your curriosity level. – Jesper Juhl Aug 10 '16 at 20:21
  • 1
    I've removed the "best practices" part of the question, because such questions are considered off-topic here. I've also replaced your title with one that actually describes the question (which is very important and possibly why you received a downvote). Don't worry that the question has been marked as a duplicate; it's still a reasonable question, just one that happens to have a potentially hard-to-find duplicate. – Kyle Strand Aug 10 '16 at 20:24
  • @JesperJuhl I'm going to go ahead and assert that asking here is actually a better solution than that. – Kyle Strand Aug 10 '16 at 20:24
  • 1
    @Kyle Strand Sure. Fine with me. But inspecting the code the compiler *actually* generates really is the only way to know for sure. And every C++ developer worth his "salt" should be able to read a bit of asm. So I don't think it's an unreasonable comment. – Jesper Juhl Aug 10 '16 at 20:28

0 Answers0