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?
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);
}
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.