+ 3
Inserting objects into set in C++
Suppose I have a structure called S. Then I have two sets s1 and s2 and an object obj of type S. struct S{ //... } S obj; set<S> s1; set<S> s2; I want to add the object to both sets so that the same object is in both sets. This would mean that later changes to the objects in s1 are done also to the object in s2 and vice versa. If I do only s1.insert(obj); s2.insert(obj); The copy constructor is called and in each set there is an independent object. What should I do? Is the only solution having sets of pointers S* instead. Thanks for help
5 odpowiedzi
+ 3
Yup you can use pointers, but probably a std::shared_ptr will be easier to manage as it will free the memory of the object when it is no longer needed, without you manually having to do it!
https://code.sololearn.com/cnB4TrpAy5dA/?ref=app
+ 2
Ketan Lalcheta I need to use it in my code for Chess Engine challenge. Each set sorts the elements in different way.
Edit:
It's almost done.
https://code.sololearn.com/c3r46fdqy6Yy/?ref=app
+ 1
Schindlabua nice one...
michal could you please share what made you to have two different copies of sets owning same object or data?
0
Schindlabua Thanks. Nice demonstration code.
0
michal thanks for sharing this... I am bit confused now..as all of the set are having same objects, what's the point of having different sets... I was eager to know that challenge result itself and now this point also... super waiting...