Why is it better to use '!=" than '<' in a vector loop? I just can't see the difference.
问题:
回答1:
Because you're using iterators, and it'll make the loop look exactly the same as other containers, should you choose to switch to other container types, such as set, list, unordered_set, etc. where < has no meaning.
回答2:
I'll assume that you mean the use of !=vector.end()
rather than <vector.size()
as that was not clear from your question.
One reason to prefer the end() version is that what you are really trying to do is to check whether you reached the end.
The idiom for doing this sort of checks for arrays in C was to check the index compared to the size, but that is a "legacy" behavior. In was then spread in the world of Java (as <array.length
) until such time that people realized that arrays are evil and that Java finally supports generics. In C++, however, there is no reason to use this idiom when you have a good collection class such as vector to work with. It's more readable, and more maintainable. For example, it makes it easier to switch to other collections if necessary, as you are still talking about the end.
回答3:
Some iterator types don't support the less-than operator -- they only support the inequality operator. That's why you'll often see the less-than operator forsaken.
回答4:
In general, I like to put code like this in a template function similar to the STL algorigthms, such that they are agnostic about what the underlying containter is.
Since < only makes sense for vectors, it would be a poor fit for a generic function. If you use <, you are locking yourself into using a vector.
回答5:
It could be that the programmer remembered a defensive coding trick: In case something goes haywire during the loop's execution, and the index/pointer/iterator goes way past the end, the loop will quietly stop upon checking '<' leaving the bug unnoticed. With != there's likely to be chaos and a crash as the loop continues with bad data, allowing an earlier fix.
回答6:
For vector iterators, it doesn't make any difference. In general, iterators may not support '<' just '==' and '!='. Hence, the most general way to test if you have not reached the end of the collection is to check if the iterator != container.end()
回答7:
Another reason: When translated into assembly, a branch-equal or branch-not-equal is generally much faster than a comparison branch.