::iterator new_end = set_difference(set1.begin(), set1.end(), set2...">

Is the following code using std :: set "legal"?

I have this code:

set<int>::iterator new_end = 
                   set_difference(set1.begin(), set1.end(),
                                  set2.begin(), set2.end(),
                                  set1.begin());
set1.erase(new_end, set1.end);

It compiles and works great in visual studio. However, in the previous question, people stated that iterators setshould be const. I do not see anything like this in the standard. Can someone tell me where he is talking, or if this is a well-defined behavior?

If this is not the case, provide the code that does what I need. Is there a way to do this without creating a temporary set?

+3
source share
5 answers

Your code breaks a couple of invariants for set_difference. From page 420 of the Josuttis Book :

  • , .
  • .

, . - , , - :

std::set<int> set3;
std::set_difference(set1.begin(), set1.end(),
                    set2.begin(), set2.end(),
                    std::inserter(set3, set3.begin()));

std::inserter - , . , , , . set3 , begin() - , .

set_difference, set3 , set1 . set3 swap set1, .

Update:

, set1, set2, :

for (std::set<int>::iterator i = set2.begin(); i != set2.end(); ++i)
{
    set1.erase(*i);
}
+7

:

std::set<int> tmp;
std::set_difference(set1.begin(), set1.end(),
                    set2.begin(), set2.end(),
                    std::inserter(tmp, tmp.begin()));
std::swap(tmp, set1);

( ).

+5

, . SGI STL Reference

  • [first1, last1) [, + n) .
  • [first2, last2) [, + n) .

, , begin() OutputIterator, . .

+4

The fifth argument set_differenceshould be OutputIterator, see the documentation .

+1
source

The C ++ standard does not explicitly state that the assignment of given iterators is prohibited, but for set_difference it indicates that "the resulting range should not overlap with any of the original ranges" (25.3.5.3).

Perhaps it worked so far only because you were lucky with the contents of set1 and set2.

+1
source

Source: https://habr.com/ru/post/1709125/


All Articles