how to delete an item from a list

I passed in a single block, and now I need to see if any of the other blocks have an identical number, and if it does, delete that block.

1
2
3
4
5
6
7
8
9
10
11
12
13
bool numberIsSame(Block block)
{  
   bool same = false;
   for (list<Block>::iterator it = blocks.begin(); it != blocks.end(); it++)
     {
        if (block.getNumber() == it->getNumber())
         {
            blocks.erase(*it);
            same = true;
         }
     }
   return same;
}

It's saying that there is no matching function to call for blocks.erase(*it)
to clarify, I need to delete the other duplicate blocks, not the one that I'm comparing to.
Last edited on
Remove the asterisk. You want to pass the iterator itself, not what it "points" to.

Also, you need to be careful about incrementing the iterator. If you erase an element, you don't want to increment the iterator since the erase method returns the updated iterator.

You should probably pass in 'block' as a const reference (no need to copy it).

It's also generally better to say ++it instead of it++. The pre-increment form is a little more efficient since it doesn't need to copy and return the old value. (This doesn't make a difference for basic types like int if you aren't using the old value, which is where people pick up the bad habit of saying it++.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool remove_duplicates(const Block& block)
{  
    bool same = false;
    for (auto it = blocks.begin(); it != blocks.end(); )
    {
        if (block.getNumber() == it->getNumber())
        {
            it = blocks.erase(it);
            same = true;
        }
        else
            ++it;
   }
   return same;
}

Last edited on
thanks!
I made a mistake. See my edit above. I changed line 8 to:

 
            it = blocks.erase(it);

what difference does that make?
It won't work correctly without it.
I originally said that 'it' will "point to the next element" after the erase, but 'it' can't do that if you don't set 'it' to the return value of erase (they could've made it a reference so you didn't need to explicitly set 'it' to the return value, but it's presumably more flexible this way).
Last edited on
Topic archived. No new replies allowed.