Is is valid to construct std::set of pointer type?

2020-04-07 03:58发布

I want to store some pointers into std::set, but the standard guide says it's invalid.

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 pq, p<=q, and > p>=q are unspecified.

It seems the <, > operators are not supported by naive pointer type, as below.

Object * a = new Object;
Object * b = new Object;
a == b; // valid
a < b; //invalid
Object * arr = new Object[10];
&arr[3] == &arr[4]; // valid
&arr[3] < &arr[4]; // valid

How can I put pointers into std::set or key of std::map? Should I define some comparison-supporting wrapper

Edit 1

Some other questions say that even though <, > are not directly supported by C++ pointers, std::less works fine with pure pointers(without any extra information). But I can't find any reference for that.

标签: c++
1条回答
够拽才男人
2楼-- · 2020-04-07 04:31

While it is true that built-in operator < only works for pointers into the same array, std::set and std::map don't use that operator - they use std::less. This, in turn, is guaranteed to impose a total order on all pointers:

[comparisons]/2 For templates less, greater, less_equal, and greater_equal, the specializations for any pointer type yield a strict total order that is consistent among those specializations and is also consistent with the partial order imposed by the built-in operators <, >, <=, >=.

查看更多
登录 后发表回答