0

Some error while doing xor to all elements of a std::set. below is partial code. Don't know much about std::transform. help pls :)

    #include<bits/stdc++.h>
    #define ll long long int 

    using namespace std;

    int main()
    {
       set<ll> e1 ;//suppose i had inserted few elements in it!
       ll x2;
       cin>>x2;
       //now i want to xor all elements of set with x2.
       std::transform(std::begin(e1), std::end(e1), std::begin(e1), [=](ll x){return x2^x;});
       return 0;
     }

Error message:

Error assignment of read-only location '__result.std::_Rb_tree_const_iterator<_Tp>::operator*()'

  • Please take some time to refresh [the help pages](http://stackoverflow.com/help), retake [the SO tour](http://stackoverflow.com/tour), and reread about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jul 08 '19 at 05:59
  • `#define ll long long int` - Don't do this! If you really want an alias for a type, use `typedef long long int ll;` or `using ll = long long int;`; don't use a preprocessor macro for such things. – Sebastian Redl Jul 08 '19 at 06:01
  • By the way, also don't forget how to create a [mcve] to show us, one that replicates the problem as well as is copyable so we can test it ourselves. Your code won't build, even if we put it in a function. – Some programmer dude Jul 08 '19 at 06:03
  • @Someprogrammerdude "Your code won't build" - You know that's kind of the point of the question, don't you? – Sebastian Redl Jul 08 '19 at 06:04
  • @SebastianRedl Well it won't build because of other and unrelated errors. Any unrelated error in the shown code will only distract from the real problem. – Some programmer dude Jul 08 '19 at 06:07
  • After your edit the code still have unrelated errors, and you should also take some time to read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Some programmer dude Jul 08 '19 at 06:08
  • @SebastianRedl i changed "#define ll long long int " to typedef long long int ll; But still the same error , i guess this is not our concern of discussion. – Bharath Choudhary Jul 08 '19 at 06:26

1 Answers1

7

You can't. A std::set doesn't allow in-place modification of its elements, so its iterators can never be written to. Thus, you can't use a std::set as the target of a std::transform.

You'd have to create a new set from the elements of the old, transforming as you go. (For example, by using a std::inserter as the target of the std::transform.)

Are you sure you can't just use std::vector?

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157