Are pointers allowed as keys in ordered STL containers?

后端 未结 4 910
遥遥无期
遥遥无期 2020-12-19 06:33

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

So I was wondering what the C++ Std has to say about

4条回答
  •  别那么骄傲
    2020-12-19 07:22

    Yes. Pointers are comparable via operator<().

    If the pointers do not point to the elements of the same array or elements within the same object the c++ standard says the behavior is unspecified [expr.rel].

    The standard says unspecified behavior means it's implementation defined [defns.unspecified].

    If your compiler guaranties a strict weak order of pointers you can use any pointer with associative containers.

    Most compilers do pointer comparison by comparing the memory addresses. On most architectures this comparison forms a strict weak order.

    Therefore it's safe to use pointers as keys.

提交回复
热议问题