Search for a set of unique pointers

I have a set of unique pointers pointing to objects. Sometimes I find some of the source pointers to these objects, so other parts of the code can do things with objects. This code does not know if pointers point to objects supported by a specific set of unique pointers or not, so I need to check if the object that the pointer points to is in a unique set of pointers.

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 an element with STL. Is there anything that satisfies my needs, or will I have to iterate over all the elements of the set manually?

+4
source share
2 answers

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

+6
source

Why not use boost :: ptr_set instread?

+2
source

Source: https://habr.com/ru/post/1482894/


All Articles