Why this get a Runtime Error?(C++)


  • 0
    C
    #include <algorithm>
    
    class Solution {
    public:
        bool containsDuplicate(vector<int>& nums) {
            if(nums.size() == 1)
                return false;
            vector<int>::iterator first = nums.begin(), last = nums.end();
            sort(first, last);
            for(vector<int>::iterator it = nums.begin(); it != last - 1 ; it++)
            {
                if(*it == *(it + 1))
                    return true;
            }
            return false;
        }
    };
    

    When I change the "it != last -1" to "it != last", the answer is correct finally. Who can tell me the reason? Thank you.


  • 0
    L

    I think iterators support '++' and '--' while they don't support '+' with a number.

    http://stackoverflow.com/questions/1057529/how-to-increment-an-iterator-by-2


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.