0

I have the following class. It has a static member _list to be shared by all instances of the class, which will be created within Class_f(). I want to use the erase function in order to erase say the last element of _list.

class myClass 
{
    private:
        static list<int> _list;
    public:
        //constructors,destructors
        void Class_f();
}

list<int> myCLass::_list;

void myClass::Class_f() 
{
    //..some code
    list<int>::iterator it1;
    it1=_list.end (); //erase for instance the last element _list
    it1=_list.erase(it1);
    //more code
}

However when compiling it outputs me an error with the message "list iterator not incrementable". Why is it giving me this error? In addition, why can't I use something simpler like _list.erase(_list.end()) so as to avoid creating an iterator.

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
Sr Incerteza
  • 143
  • 3

3 Answers3

5

_list.end() is not an iterator to the last element. It is the one-past-the-end iterator. You can't really do anything with it. C++'s iterator ranges are half-open.

However, if you're really getting a compiler error, then something is wrong that you haven't shown us.

More likely you're seeing a debugger message from runtime, wherein the standard library implementation in debug mode has very kindly discovered your attempt to increment _list.end() (which would have undefined behaviour), which happens during the preparation of return value for _list.erase(it1) and told you not to be such a doofus. :)

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • sorry, I should have meant "debugger message". At any rate, the error comes precisely from accessing an element past the size of list. How can I access then the last element? – Sr Incerteza May 12 '16 at 10:23
  • @SrIncerteza: Did you lose your internet access? You can simply read the documentation for `std::list` to find out. The other answers have told you which to use, also (though I prefer to leave a little something for you to discover on your own). – Lightness Races in Orbit May 12 '16 at 10:31
4

Firstly, list.end() gives you a "iterator referring to the past-the-end element". So calling erase(list.end()) will not work.

Secondly, use list.pop_back() to delete the last element. List.pop_back()

KaziJehangir
  • 295
  • 1
  • 3
  • 9
3

With _list.pop_back() you can delete the last element, which is maybe more convenient than to use the erase function.

http://www.cplusplus.com/reference/list/list/pop_back/

Chiel
  • 6,006
  • 2
  • 32
  • 57