Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 954
Taeyeong Jeong Avatar asked Dec 26 '18 04:12

Taeyeong Jeong


People also ask

How do you declare a pointer type?

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.

Can pointers be any type?

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.

How do you make a pointer in C++?

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.

Is 1 a valid pointer?

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.


1 Answers

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

like image 77
Igor Tandetnik Avatar answered Oct 13 '22 00:10

Igor Tandetnik