ort23
ort23

Reputation: 83

Delete list element from class

I try to delete list element and always get error message.

Firstly I have this class structure :

Class X
{ public:
  ID;
  name;
}

then I have list container.

Now, I want to delete specific element from container.

void delete ( list<X> a , X b )
{

list<X>::iterator itr;

for ( itr =a.begin() ; itr != a.end() ; itr++ )
{
    if ( *itr.ID == b.ID )
    { a.erase(itr) ; }
}
}

But, I get error:

" iterator doesn't have ID ".

How can I fix it?

Upvotes: 0

Views: 93

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

This is because the dot operator . is "stronger" than the dereference operator *. According to this table, dot has a precedence of two, while dereference asterisk * has a precedence of three (lower is stronger). This means that without the parentheses the compiler tries to get iterator's member ID, and then dereference the value of ID. This is not possible, because the iterator has no member called ID.

You need to put parentheses to enforce the precedence that you want:

if ( (*itr).ID == b.ID )

Alternatively, you can use the -> operator to dereference the iterator:

if ( itr->ID == b.ID )

Note: C++ Standard Library provides a way to do this without a loop:

a.erase(
    remove_if(
        a.begin()
    ,   a.end()
    ,   [](X x){ return x.ID == b.ID; }
    )
,   a.end()
);

Demo on ideone.

Upvotes: 1

user3360398
user3360398

Reputation:

i prefer to use itr->ID instead of *itr.ID. the later is a little confusing sometime.

Upvotes: 0

Related Questions