I have a set of unique pointers pointing to objects. Occasionally, I will reveal some of the raw pointers to these objects so other parts of the code can do stuff with the objects. This code does not know whether the pointers are pointing to objects maintained by a certain set of unique pointers or not, so I need to check whether the object pointed to by a pointer is in a unique pointer set.
In simple code:
int* x = new int(42);
std::set<std::unique_ptr<int>> numbers;
numbers.insert(std::unique_ptr<int>(x));
numbers.find(x) // does not compile
I understand why the code does not compile, but I cannot think of a way to search for the element with the STL. Is there anything that caters to my needs or will I have to iterate over all elements of the set manually?
You can use std::find_if
like this:
std::find_if(numbers.begin(), numbers.end(), [&](std::unique_ptr<int>& p) { return p.get() == x;});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With