【问题标题】:Is it possible to create a set of pointers to objects in cpp?是否可以在 cpp 中创建一组指向对象的指针?
【发布时间】:2019-03-05 05:49:45
【问题描述】:

在尝试创建 cpp 对象集时,我遇到了这个问题

How do i insert objects into STL set 但我的疑问是,有没有办法不在集合中存储实际对象而是指向它们的指针,并且仍然能够维护集合的唯一实体属性。

【问题讨论】:

  • std::set 允许您指定自定义比较器。在您的情况下,您可以为进行深度对象比较的指针创建一个包装器类型,或者使用带有自定义比较器的普通指针,其中比较器取消引用指针并比较对象。

标签: c++ c++11 data-structures set


【解决方案1】:

set 模板参数化为

template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;

要将 指针 存储到 T 类型,但要确保 唯一,您只需提供适当的 @987654325 @functor,可以通过比较指针的解引用值来比较指针。

例如,对于指向some_type 的指针,我们可以使用类似:

class comparison {
   bool operator()(const some_type* lhs, const some_type* rhs) const {
        return *lhs < *rhs;
    }
};

然后将集合声明为

std::set<some_type*, comparison> s;

【讨论】:

    【解决方案2】:

    您可以在 std::set 中使用自定义比较器来取消引用对象并进行比较。

    bool compare_int(const int*& l, const int*& r) {
        return (*l) < (*r);
    }
    std::set<int*, compare_int> intSet;
    
    int   myInt     = 5;
    int*  myIntPtr  = &myInt;
    
    inSet.insert(myIntPtr);
    

    【讨论】:

      猜你喜欢
      • 2020-01-18
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多