是否允许指针作为有序 STL 容器中的键?

2022-01-24 00:00:00 pointers containers standards c++

this other question询问如何比较指针应该如何解释 wrt C++ Std.

There's this other question asking about how comparing pointers is supposed to be interpreted wrt the C++ Std.

所以我想知道 C++ 标准对在有序标准库 (STL) 容器中使用指针作为键有什么看法――即是否允许拥有

So I was wondering what the C++ Std has to say about using pointers as keys in ordered standard library (STL) containers -- i.e. is one allowed to have

std::map

这是由于 std::less内置运算符 < 的规范造成的吗?

and is this due to the specification of std::less or builtin operator <?

推荐答案

是的,因为它使用了 std::less,即使 也需要产生全序. 没有.(< 将被允许将来自不同序列的不同指针视为相同,如果您插入来自不同序列的指针,这将导致 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).

相关文章