0

I am trying to practice basic algorithm and am keep receiving segmentation error while running on my mac vscode.

Can any one help?

#include <iostream>
#include <vector>

using namespace std;

int removeDuplicates(vector<int> &nums)
{
    vector<int>::iterator itr = nums.begin();
    int prev = *itr;
    for(itr = ++itr ; itr != nums.end() ; itr++) {
        if(*itr == prev) {
            nums.erase(itr);
        } else {
            prev = *itr;
        }
    }
    itr = nums.begin();
    for(; itr != nums.end(); itr++) {
        cout<<*itr<<endl;
    }
    return 1;
}

using namespace std;
int main() {
    vector<int> test1;
    test1.push_back(1);
    test1.push_back(1);
    test1.push_back(1);
    test1.push_back(2);
    test1.push_back(2);
    test1.push_back(3);
    test1.push_back(3);
    test1.push_back(3);
    removeDuplicates(test1);
}

The problem in the terminal is [Done] exited with code=139 in 0.59 seconds, where code=139 seems to imply the segmentation error.

Is this the problem with my local running environment or is it the problem with the logic?

Any help would be appreciated.

jamesdean
  • 21
  • 5
  • [`std::sort`](https://en.cppreference.com/w/cpp/algorithm/sort) followed by [`std::unique`](https://en.cppreference.com/w/cpp/algorithm/unique)? Or considering that you add elements to the vector in an ordered fashion already, just `std::unique`. – Some programmer dude May 25 '20 at 07:06
  • It always makes me smile when beginners wonder if the problem might be something other than their faulty code. – john May 25 '20 at 07:09
  • @john thanks john haha you are correct :) fixed my code with comment of other great programmers! – jamesdean May 25 '20 at 07:23
  • @john and then when you *really* stumble across a fault caused by something or someone else you continue wondering for too long about what could be wrong with the code – E. van Putten May 25 '20 at 07:40
  • @jamesdean Great, I think everyone has made the mistake you made at some time (several times in my case). – john May 25 '20 at 07:54

1 Answers1

1

You can use the return value from erase function to be the new value of itr. You have to do this because the erase action invalidates the iterator.

E. van Putten
  • 615
  • 7
  • 17