制作一组指针以使用底层注入的比较标准,C++

Edu*_*yan 1 c++ sorting set shared-ptr

我想std::set是否shared_ptr's比较指针对象,而不是指针。
我有这个例子:

std::shared_ptr<std::string> s(new std::string("abc"));
std::shared_ptr<std::string> p(new std::string("abc"));
std::set<std::shared_ptr<std::string>> S;
S.insert(s);
S.insert(p);
std::cout << S.size();
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我将相同的元素放入set但输出 2.
如何使 set 的插入使用底层字符串的比较标准?如果它不是字符串而是更复杂的对象呢?

for*_*818 5

的第二个模板参数std::set是要使用的比较器的类型(默认为std::less<Key>):

#include <iostream>
#include <memory>
#include <set>
#include <string>

struct deref_less {
  bool operator()(const auto& a, const auto& b) const { return (*a) < (*b); }
  using is_transparent = void;
};

int main() {
  std::shared_ptr<std::string> s(new std::string("abc"));
  std::shared_ptr<std::string> p(new std::string("abc"));
  std::set<std::shared_ptr<std::string>, deref_less> S;
  S.insert(s);
  S.insert(p);
  std::cout << S.size();
}
Run Code Online (Sandbox Code Playgroud)

输出

1
Run Code Online (Sandbox Code Playgroud)

auto为了方便使用 C++20,在比较器之前的参数有点冗长。using is_transparent = void;启用例如set::find接受 a的重载std::unique_ptr<std::string>(参见 Godbolt 示例)。

  • `compare_shared` 不是最好的名字(`compare` 往往返回负数、空值、正数),那么 `deref_less` 怎么样? (2认同)