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