I have a std::set
of std::shared_ptr
s. I want to be able to use a builtin method such as find
in order to efficiently search for elements within this set. However since shared pointers to equal objects aren't equal, doing so doesn't work.
#include <iostream>
#include <memory>
#include <set>
#include <string>
auto main() -> int {
auto a = std::make_shared<std::string>(std::string("a"));
auto b = std::make_shared<std::string>(std::string("a"));
// shared pointers to equal objects aren't equal
std::cout << (a == b) << std::endl;
}
Are there any other ways that I can use to achieve this functionality, preferably without implementing my own version of the algorithm? This is the sort of thing I'm looking for.
#include <iostream>
#include <memory>
#include <set>
#include <string>
auto main() -> int {
std::set<std::shared_ptr<std::string>> thing;
thing.insert(std::make_shared<std::string>(std::string("a")));
// Because the pointers aren't equal, this will be equal to the end iterator,
// meaning the search failed.
std::cout
<< (thing.find(std::make_shared<std::string>(std::string("a"))) != thing.end())
<< std::endl;
}