0

I have a std::set of std::shared_ptrs. 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;
}
Miguel Guthridge
  • 1,444
  • 10
  • 27
  • 1
    Cribbed from the duplicate: `auto cmp = [](auto const& a, auto const& b) { return *a < *b; };` and `std::set, decltype(cmp)> thing(cmp);`. – Eljay Jul 30 '22 at 16:59
  • Why would you have a set of shared pointers at all? std::set would be good enough. std::string allocates memory if it needs to, the set will take ownership of the string. Adding a shared_ptr to a set will do the same so the string will share the lifetime of the set in both cases. Just adding a shared_ptr overcomplicates things. – Pepijn Kramer Jul 30 '22 at 17:10
  • @PepijnKramer because I need to due to other aspects of my code that are far beyond the scope of my question. – Miguel Guthridge Jul 30 '22 at 17:21

0 Answers0