Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are two problems in your code.</p> <p><em>First</em>, you need return a value in the following function, or simply make it return void.</p> <pre><code>// you should return a value here or make it return void int outputSet(int i) { cout &lt;&lt; i &lt;&lt; endl; } </code></pre> <p><em>Second</em>, the iterators in the following iterations of your for-loop are <strong><em>invalidated</em></strong> once you remove the current one. Once an element is removed, its iterator i is also invalidated, so as to the following iterators based on ++i;</p> <p>And you'll get run-time error because iterator i now points to You need somehow "reset" it.</p> <p><strong>MSVC Implementation</strong></p> <pre><code>for (set&lt;int&gt;::iterator i = n1Ar.begin(); i != n1Ar.end(); ++i) { it = n2Ar.find(*i); if (it != n2Ar.end()) { list.insert(*i); // the following iterators become invalidated after the // current one is removed. You need reset it like // i = n1Ar.erase(i); n1Ar.erase(i); n2Ar.erase(it); } else { it = n3Ar.find(*i); if (it != n3Ar.end()) { list.insert(*i); // the following iterators become invalidated after the // current one is removed. You need reset it like // i = n1Ar.erase(i); n1Ar.erase(i); n3Ar.erase(it); } } } </code></pre> <p><strong>Edit</strong>: Note that returning a new iterator from set::erase() is not a Standard way. That's mainly for the purpose of performance.</p> <p><strong>A More Portable Solution</strong></p> <p>The basic idea is to correctly set the next iterator before removing the current one.</p> <pre><code> set&lt;int&gt;::iterator i = n1Ar.begin(); while (i != n1Ar.end()) { it = n2Ar.find(*i); if (it != n2Ar.end()) { // the trick is to use "i++" where i is incremented by one while "old" i // is removed. list.insert(*i); n1Ar.erase(i++); n2Ar.erase(it); } else { it = n3Ar.find(*i); if (it != n3Ar.end()) { list.insert(*i); n1Ar.erase(i++); n3Ar.erase(it); } else { ++i; } } } </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