Chris
Chris

Reputation: 7184

Searching a set of unique pointers

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?

Upvotes: 11

Views: 4952

Answers (2)

mumu
mumu

Reputation: 307

Why not use boost::ptr_set instead?

Upvotes: 5

Asha
Asha

Reputation: 11232

You can use std::find_if like this: std::find_if(numbers.begin(), numbers.end(), [&](std::unique_ptr<int>& p) { return p.get() == x;});

Upvotes: 12

Related Questions