0

Is it okay practice to define ordered associative containers of pointers (either built-in or class-type ones) despite the fact that, as far as I can tell from the standard, relational operators on (non-array objects et al.) pointers are undefined?

From 5.9 of the c++11 standard:

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

Since ordered containers (map, set, multimap and multiset) use the < operator by default to provide a total order it compiles fine to create a set of pointers. Then again if the relational operators for pointers are truly unspecified it could be that p<q and p>q both test false or true meaning this may not be a good idea for the ordering of a set. I would've probably accepted that it is a bad idea if it wasn't for the fact that an example in my book (C++ Primer 5th ed chapter 13.4) defines a set of pointers for a class type Folder*, i.e. set<Folder*> seemingly with no comment on my concern.

AntiElephant
  • 1,227
  • 10
  • 18

2 Answers2

2

The ordered associative containers do not use operator< directly, they use std::less, which is well defined and establishes a total ordering for pointer types, even when operator< isn't.

So, it is fine to instantiate std::set or std::map with pointer types as keys.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

"Yes, because it uses std::less, which is required to result in a total order even if < doesn't. (< would be allowed to treat different pointers from distinct sequences as equal, which would result in an odd behaviour of map etc if you insert pointers from different sequences)." -etarion

Source of quote: Are pointers allowed as keys in ordered STL containers?

Also, this question is a duplicate of that question.

Community
  • 1
  • 1
LostMikely
  • 130
  • 10