指针的有序关联容器

Ordered associative containers of pointers

定义指针的有序关联容器(内置或 class 类型的容器)是否可行,尽管事实上,据我所知,从标准来看,关系运算符在 (非数组对象等)指针未定义?

来自 c++11 标准的 5.9:

  1. If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<q, p>q, p<=q, and p>=q are unspecified.

由于有序容器(map、set、multimap 和 multiset)默认使用 < 运算符来提供总顺序,因此它可以很好地编译以创建一组指针。然后,如果指针的关系运算符确实未指定,则可能 p<qp>q 都测试 falsetrue,这意味着这可能不是排序的好主意的 set。如果不是因为我书中的一个示例(C++ Primer 第 5 版第 13.4 章)为 class 类型 [=20] 定义了一组指针,我可能会接受这是一个坏主意=],即 set<Folder*> 似乎没有对我的担忧发表评论。

有序关联容器不直接使用 operator<,它们使用 std::less,它定义明确并为指针类型建立了总顺序,即使 operator< 不是.

所以,实例化std::setstd::map,指针类型作为键就可以了。

"Yes, because it uses std::less, which is required to result in a total order even if < doesn't. (< would be allowed to treat different pointers from distinct sequences as equal, which would result in an odd behaviour of map etc if you insert pointers from different sequences)."-etarion

引用来源:Are pointers allowed as keys in ordered STL containers?

此外,这个问题与那个问题重复。