Home > OS >  Why don't elements from my list get erased
Why don't elements from my list get erased

Time:06-08

I have to write a function that erases an element out of the list if it's bigger than the previous element.(The previous element is the one which points to the next element before deletion)

I think I've basically finished it but I don't know why it doesn't erase 5 out of my list.

void deleteBigger(list<int> s){
    list<int>::iterator test;
    for(test = s.begin(); test != s.end(); test  ){
        int sk1=*test;
        cout<<sk1<<endl;
        test--;
        int sk2=*test;
        cout<<sk2<<endl;
        if(sk1>sk2){
            cout<<"Im here!\n";
            s.erase(test);
        }
        test  ;
    }
}

It doesn't give an error or anything it just doesn't erase. I tried to test the erase method in the main function of the program, and there it worked fine.

CodePudding user response:

There are three problems with your code:

  1. Your list is passed by value, not reference. So you are changing a copy of your list and it doesn't alter the original container
  2. You try to remove an element from a list while iterating it. Edit: As @Remy Lebeau mentioned in the comments, to be more precise it's a problem because you don't update the iterator properly, but not a problem on its own. Be advised, that when you remove an element from a list, the iterator which pointed to the erased element is considered invalidated.
  3. Upon the first iteration, you decremented the iterator out of the container's bounds

Summing it up, what you might want to have here looks something like this:

void deleteBigger(std::list<int> &s) {
    using namespace std;

    if (s.empty()) {
        return;
    }

    for(auto test = next(s.cbegin()); test != s.cend();   test){
        while ((*test > *prev(test)) && (test != s.cend())) {
            test = s.erase(test);
        }
    }
}

CodePudding user response:

I've copied your code and it doesn't work. The problem is your iterator pointer "test". You can't degree a pointer at the begin. The only thing you can do is use a control.

Note: it's wrong decrement a pointer because you are decrementing of (32 bits) the index of memory. In this case there is overriding -- operator that saves your program but be careful next times

Control your program. It's important use a debugger editor where you can stop the program at certain point and control the value of the variables

  •  Tags:  
  • c
  • Related