唯一指针的映射,带有原始指针的 .at()

Map of unique pointers, .at() with a raw pointer

本文关键字:指针 at 原始 映射 唯一      更新时间:2023-10-16

>假设我有一张地图:

std::map<std::unique_ptr<SomeType>, SomeOtherType> map;

显然,这是行不通的,因为我们地图的关键值是唯一的 ptr,而不是原始的:

//a pointer from somewhere else in the code
SomeType* p = ...;
auto result {map.at(p)};

相反,人们可以做的是使用 std::unique_ptr.get() 做这样的事情:

SomeType* p = ...;
for(auto& entry : map) {
if(entry.first.get() == p) {
//do whatever
}
}

然而,这是一种非常丑陋且可能效率低下的方式。我的问题只是在这种情况下是否有办法以某种方式使用 .at() 函数。

在 C++ 14 中,您可以提供一个透明的比较器

template<typename T>
struct PtrCompare
{
std::less<T*> less;
using is_transparent = void;
bool operator()(T* lhs, const std::unique_ptr<T> & rhs) const { return less(lhs, rhs.get()); }
bool operator()(const std::unique_ptr<T> & lhs, T* rhs) const { return less(lhs.get(), rhs); }
bool operator()(const std::unique_ptr<T> & lhs, const std::unique_ptr<T> & rhs) const { return less(lhs.get(), rhs.get()); }
}
std::map<std::unique_ptr<SomeType>, SomeOtherType, PtrCompare<SomeType>> map;

这对at没有帮助,但确实允许您根据可以比较的任何内容进行find

SomeType* p = ...;
if (auto it = map.find(p))
{
// use it->second
}
else
{
throw std::out_of_range;
}