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.
The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double) too. Naming Convention of Pointers: Include a "p" or "ptr" as prefix or suffix, e.g., iPtr, numberPtr, pNumber, pStudent.
A pointer type variable holds the address of a data object or a function. A pointer can refer to an object of any one data type; it cannot refer to a bit field or a reference.
Create a pointer variable with the name ptr , that points to a string variable, by using the asterisk sign * ( string* ptr ). Note that the type of the pointer has to match the type of the variable you're working with.
On any real world desktop or server system, -1 cast to a pointer is equivalent to the all-bits-one pointer representation, and it is not a valid pointer.
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
, andgreater_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<
,>
,<=
,>=
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With