6

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.

1 Answers1

10

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 <, >, <=, >=.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • I was wondering why `<` cannot compare pointers to elements to different arrays. Why can't it just compare the memory address like `std::less` – Gaurav Sehgal Dec 26 '18 at 05:05
  • 1
    @GauravSehgal If I had to guess, I'd suspect it has something to do with [segmented memory](https://en.wikipedia.org/wiki/Memory_segmentation) architectures that were prevalent at the time C++ was being standardized. – Igor Tandetnik Dec 26 '18 at 05:09
  • @GauravSehgal different objects could have different storage and address schemes. – user4581301 Dec 26 '18 at 05:09