C++ programming specification: use != instead of < in for loop

In the conditional judgment of the index i in the for loop, we need to use != instead of < for the following two reasons:

(1) Many STL containers in C++ define iterators and != operators, but most of them do not define < operators and subscript operations. Considering the generality of programming styles (all containers provided in the standard library are valid), we need to get in the habit of using iterators and !=.

(2) The judgment speed of using != may be faster than using < (I am not sure if it is right, it may be related to the underlying logic of the computer).

Code example:

class Solution {
    
    
public:
    int removeDuplicates(vector<int>& nums) {
    
    
        int k=1;
        const int length=nums.size();
        // 不要写成 for(int i=1;i!=nums.size();i++),否则每次循环都要计算一次nums.size()
        for(int i=1;i!=length;i++)
            if(nums[i]!=nums[k-1]){
    
    
                nums[k]=nums[i];
                k++;
            }
        return k;
    }
};

Guess you like

Origin blog.csdn.net/qq_43799400/article/details/130514575