title: How to get rid of weak_ptrs in a container
body: <p>I have a class that stores weak_ptrs in a container and later does something if the weak_ptr is not expired:</p>
  
  <pre><code>class Example
  {
  public:
      void fill(std::shared_ptr&lt;int&gt; thing)
      {
          member.push_back(thing);
      }
      void dosomething() const
      {
          for (const auto&amp; i : member)
              if (!i.expired())
                  ;// do something. the weak_ptr will not be locked
      }
  private:
      std::vector&lt;std::weak_ptr&lt;int&gt;&gt; member;
  };
  </code></pre>
  
  <p>If <code>Example</code> is an object that lives forever and <code>fill</code> is used regularily, the vector allocates memory for elements continously, but they are never removed after they expired.</p>
  
  <p>Is there any automatic C++ way to get rid of the expired weak_ptrs in the container or is there a better way to store a variable number of them?</p>
  
  <p>My naive way would be to iterate over the container each time <code>fill</code> is called and remove all the expired weak_ptrs. In scenarios where <code>Example</code> has many elements in the container and fill is frequently called this seems to be very inefficient.</p>