In c++ primer, pg 95 the author says that c++ programmers tend to use != in preference of < when writing loops.
for (vector<int>::size_type i = 0; i != 10; ++i) is preferred instead of for (vector<int>::size_type i = 0; i < 10; ++i)
I read the same thing in accelerated c++. Can someone explain the rationale behind this
The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .
The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. In fact, !! x is a common idiom for forcing a value to be either 0 or 1 (I personally prefer x != 0 , though).
C++ Algorithm Function equal() C++ Algorithm equal()function compares the elements in both the containers and returns a true value if all the elements in both the containers are found to be matching. The first range is from [first1,last1) and the second starts from first2.
In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1.
When using some kinds of STL iterators (those that aren't random access), you must use !=
:
for (map<int,int>::iterator i = a.begin(); i != a.end(); ++i) ...
However, I don't see any reason to prefer !=
for well-ordered scalar types as in your example. I would usually prefer <
for scalar types and !=
for all iterator types.
It's a habit for generic programming; for example, you can easiely use <
with indices, but you cannot use that with all iterator types. A list iterator cannot efficiently implement <
- however, !=
can be implemented for even the simplest of iterator types. Therefore, it is a good habit to always use the most generic comparison - it makes your code more resilient to change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With