唯一指针的映射,带有原始指针的 .at()
Map of unique pointers, .at() with a raw pointer
>假设我有一张地图:
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;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 唯一指针的映射,带有原始指针的 .at()
- 如何使用 QVector at or operator[] 获取指向元素的指针