Why is it better to use '!=" than '<' in a vector loop? (C++)

后端 未结 7 1314
没有蜡笔的小新
没有蜡笔的小新 2021-01-02 04:53

Why is it better to use \'!=\" than \'<\' in a vector loop? I just can\'t see the difference.

7条回答
  •  情话喂你
    2021-01-02 05:41

    I'll assume that you mean the use of !=vector.end() rather than 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.

提交回复
热议问题