Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 641
Chris Avatar asked May 27 '13 06:05

Chris


1 Answers

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

like image 150
Asha Avatar answered Oct 30 '22 01:10

Asha