Note that there are some explanatory texts on larger screens.

plurals
  1. PONow to remove elements that match a predicate?
    text
    copied!<p>I have a source container of strings I want to remove any strings from the source container that match a predicate and add them into the destination container.</p> <p><code>remove_copy_if</code> and other algorithms can only reorder the elements in the container, and therefore have to be followed up by the <code>erase</code> member function. My book (Josuttis) says that <code>remove_copy_if</code> returns an iterator after the last position in the destination container. Therefore if I only have an iterator into the destination container, how can I call <code>erase</code> on the source container? I have tried using the size of the destination to determine how far back from the end of the source container to erase from, but had no luck. I have only come up with the following code, but it makes two calls (<code>remove_if</code> and <code>remove_copy_if</code>).</p> <p>Can someone let me know the correct way to do this? I'm sure that two linear calls is not the way to do this.</p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;functional&gt; using namespace std; class CPred : public unary_function&lt;string, bool&gt; { public: CPred(const string&amp; arString) :mString(arString) { } bool operator()(const string&amp; arString) const { return (arString.find(mString) == std::string::npos); } private: string mString; }; int main() { vector&lt;string&gt; Strings; vector&lt;string&gt; Container; Strings.push_back("123"); Strings.push_back("145"); Strings.push_back("ABC"); Strings.push_back("167"); Strings.push_back("DEF"); cout &lt;&lt; "Original list" &lt;&lt; endl; copy(Strings.begin(), Strings.end(),ostream_iterator&lt;string&gt;(cout,"\n")); CPred Pred("1"); remove_copy_if(Strings.begin(), Strings.end(), back_inserter(Container), Pred); Strings.erase(remove_if(Strings.begin(), Strings.end(), not1(Pred)), Strings.end()); cout &lt;&lt; "Elements beginning with 1 removed" &lt;&lt; endl; copy(Strings.begin(), Strings.end(),ostream_iterator&lt;string&gt;(cout,"\n")); cout &lt;&lt; "Elements beginning with 1" &lt;&lt; endl; copy(Container.begin(), Container.end(),ostream_iterator&lt;string&gt;(cout,"\n")); return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload