C++ 具有原始指针的唯一指针.at()的映射

C++ 具有原始指针的唯一指针.at()的映射,c++,dictionary,pointers,std,unique-ptr,C++,Dictionary,Pointers,Std,Unique Ptr,假设我有一张地图: std::map<std::unique_ptr<SomeType>, SomeOtherType> map; 我们可以使用std::unique\u ptr.get执行类似的操作: SomeType* p = ...; for(auto& entry : map) { if(entry.first.get() == p) { //do whatever } } 然而,这是一种非常丑陋而且可能效率低下的方式。

假设我有一张地图:

std::map<std::unique_ptr<SomeType>, SomeOtherType> map;
我们可以使用std::unique\u ptr.get执行类似的操作:

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

然而,这是一种非常丑陋而且可能效率低下的方式。我的问题是,在这种情况下,是否有一种使用.AT函数的方法。在C++ 14中,

< p>,可以提供透明的比较器< /p>
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;

C++ 14,可以提供透明的比较器< /P>

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;

使用指针作为键很少需要,而且常常是错误的。如果有两个指针指向两个不同的对象实例,但对象实例在其他方面是相等的,它们作为键仍然是不同的,因为指针才是键,不是他们指向的对象。@Someprogrammerdude这里有两个指针指向同一个对象。为什么你认为你需要的键是std::unique\u ptr而不仅仅是某个类型?我在创建的网络程序中使用了这样的映射。映射存储一个TCP套接字对象作为其密钥,另一个包含其他信息(如IP地址)的对象作为其映射值。既然您提到了它,我实际上不认为SomeType是唯一指针的原因。我想我是这样做的,因为出于其他原因,映射值确实必须是唯一的指针。感谢您指出这一点。尽管您仍然认为@Caleth的解决方案是最好的,但您可以使用unique_ptr和其他类定义您的结构,并使用或int或其他类型的映射。使用指针smart或not作为键很少需要,而且常常是错误的。如果有两个指针指向两个不同的对象实例,但对象实例在其他方面是相等的,它们作为键仍然是不同的,因为指针才是键,不是他们指向的对象。@Someprogrammerdude这里有两个指针指向同一个对象。为什么你认为你需要的键是std::unique\u ptr而不仅仅是某个类型?我在创建的网络程序中使用了这样的映射。映射存储一个TCP套接字对象作为其密钥,另一个包含其他信息(如IP地址)的对象作为其映射值。既然您提到了它,我实际上不认为SomeType是唯一指针的原因。我想我是这样做的,因为出于其他原因,映射值确实必须是唯一的指针。感谢您指出这一点。虽然您仍然认为@Caleth的解决方案是最好的,但您可以使用unique_ptr和其他类定义您的结构,并使用或int或其他类型的映射感谢您!请注意,要在GCC 8+中编译此代码,应将const添加到调用运算符中。谢谢!请注意,要在GCC 8+中进行编译,应将const添加到调用运算符中
SomeType* p = ...;
if (auto it = map.find(p))
{
    // use it->second
}
else
{
    throw std::out_of_range;
}