24 ms·
it tends to obscure the actual logic the programmer intended, making code harder to read for(int i = 0; i < vec.size(); i++) // do something with v
by userbinator 7y ago
it tends to obscure the actual logic the programmer intended, making code harder to read
for(int i = 0; i < vec.size(); i++)
// do something with vec[i]
That's even simpler and more in line with what vectors are usually used for, and when it comes time to debug, you don't have to deal with the template-hell that is the standard library iterator-framework. The for : may look simpler at first glance, but quick turns into a nightmare when you're trying to do some deep debugging (and if you haven't had to debug by reading the Asm, I think you haven't done enough C++...) because it obscures a significant amount of complexity which really shouldn't be necessary anyway.
- jcelerier 7y agoyour simpler code is at least theoretically less efficient - you get an int to size_t (unsigned long long) conversion twice (once when comparing with size() and once when accessing the vec) and you compare to the size every time. This looks like it is irrelevant in release mode, but it may end up having an effect on your debug performance which is important in many domains. You would have to write for(std::size_t i = 0, N = vec.size(); i < N; i++) // do something with vec[i] instead if you still insist in raw loops. But if you look at https://gcc.godbolt.org/z/8JwJbw https://gcc.godbolt.org/z/8JwJbw, you will notice that the range-based loop is actually the one which will produce the smaller code which may translate into more efficiency, and is also more readable.
- Too 7y agoChange the vector to std::list and you loose the [i] operator. Now how would you rather iterate that? 5 lines of begin() end() *it++, or a 2-liner foreach. We haven't even brought const- and reference-correctness into the picture here. That makes the number of potential errors in the it-example even worse. There are also iterators where the size is not known up front, streaming input for example. The point is, some features in a language can reduce complexity and improve readability (like foreach) while others can increase it (move assignment constructors?). This is only looking at it from a developers point of view though, compiler authors might disagree.