title: Removing an element from a composite pattern structure
body: <p>Suppose we have the simplest structure, classes <code>Component</code>, <code>Leaf : Component</code> and <code>Composite : Component</code>. Each object of <code>Leaf</code> class has an <code>int id</code> which gives it its identity. The composite class would have sth like:</p>
  
  <pre><code>class Composite : public Component
  {
  public:
      void removeComponent(Component*);
  // other stuff
  private:
      std::vector&lt;Component*&gt; coll;
  };
  </code></pre>
  
  <p>And leaf class sth like:</p>
  
  <pre><code>class Leaf : public Component
  {
  public:
      //stuff
      int getID();
  private:
      int id;
  };
  </code></pre>
  
  <p>And the question is how to define the function <code>removeComponent(Component* cmp)</code>. cmp is actually a <code>Leaf</code>, but I need to access the <code>Component</code> vector coll, so it needs to be a <code>Component</code> (I think). The removeComponent method takes a <code>Leaf</code> object, and removes all other Leaves with the same ID, from the whole structure. </p>
  
  <p>Now, I have thought of two ways (neither of which works :P):</p>
  
  <p><em><strong>First</em></strong></p>
  
  <pre><code>void Composide::removeComponent(Component* cmp)
  {
      std::vector&lt;Component*&gt;::const_iterator it;
      for(it = coll.begin(); it != coll.end(); ++it)
      {
          (*it)-&gt;removeComponent(cmp);
      // where removeComponent is defined as virtual in Component, but
      // the problem is that Leaf cannot erase itself from the collection
      }
  
  }
  </code></pre>
  
  <p><em><strong>Second</em></strong></p>
  
  <pre><code>void Composide::removeComponent(Component* cmp)
      {
          std::vector&lt;Component*&gt;::const_iterator it;
          for(it = coll.begin(); it != coll.end(); ++it)
          {
              if((*it)-&gt;equals(*cmp))
              it = erase(it);
          // But here I can't define equals function for Composite elements,
      // so then I'd have to make functions which return the type of Component,
      // and in case of Composite call recursively the function and
      // in the case of Leaf call the equals() function and erase if needed.
      // This however looks like really bad OOP practice, and I'd like to avoid
      // using those methods which return type..
          }
  
      }
  </code></pre>
  
  <p>There has to be a neat, nice way to do this. I kind of think that the method should look something like the upper-mentioned 1st way, only I really don't know how to enable the <code>Leaf</code> to delete itself from the vector. Help me please? :)</p>