2

I am getting a compilation error for this simple piece of code

"Error 1 error C3892: 'std::_Tree_const_iterator<_Mytree>::operator *' : you cannot assign to a variable that is const"

std::set<int> s1;
std::set<int> s2;
std::set<int> s3;
std::set_union(s1.begin() , s1.end() , s2.begin() , s2.end() , s3.begin());

I followed this page cant see what i did wrong.

http://www.cplusplus.com/reference/algorithm/set_union/

2 Answers 2

4

The items in a set are effectively const. You can't change them in the set, because doing so might change their order with respect to other set members (which would violate the invariants). To modify an item, you normally remove it from the set, modify it, then insert the modified version back into the set (ensuring it's in the correct order when it's re-inserted).

At least if memory serves, the standard doesn't require that a set<T>::iterator be equivalent to a const_iterator, but does allow it, and your compiler apparently takes advantage of that.

In any case, what you almost certainly want is an insert_iterator to put the results from the algorithm into the set.

std::set_union(s1.begin() , s1.end() , s2.begin() , s2.end() , std::inserter(s3, s3.begin());
4

s3.begin() needs to be wrapped in std::inserter(s3, s3.begin()).

std::inserter constructs an insert iterator which calls insert for you. However, a more efficient way than std::set_union would be:

s1.insert(s2.begin(), s2.end()); 

Unless you didn't want to modify s1 and wanted a separate set.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.