In C++ primer 5 ed. page 172:
"We cannot use the relational operators on pointers to two unrelated objects:
int i = 0, sz = 42;
int *p = &i, *e = &sz;// undefined: p and e are unrelated; comparison is meaningless!
while (p < e) ".
But if I run the same code on GCC or CLANG it compiles fine even against wall
flag.
- On page 712: about function objects:
"One important aspect of these library function objects is that the library guarantees that they will work for pointers. Recall that comparing two unrelated pointers is undefined (§ 3.5.3, p. 120). However, we might want to sort a vector of pointers based on their addresses in memory. Although it would be undefined for us to do so directly, we can do so through one of the library function objects:
vector<string *> nameTable; // vector of pointers
// error: the pointers in nameTable are unrelated, so < is undefined
sort(nameTable.begin(), nameTable.end(),
[](string *a, string *b) { return a < b; });
// ok: library guarantees that less on pointer types is well defined
sort(nameTable.begin(), nameTable.end(), less<string*>());
It is also worth noting that the associative containers use less<key_type>
to order
their elements. As a result, we can define a set
of pointers or use a pointer as the
key in a map
without specifying less directly."
I don't know how
less<string*>
library function object guarantees the comparison although it only applies<
into the arguments of element type?!In his example
nameTable
; it is a vector of pointers-to-strings thus they are contiguous in memory so how could it be undefined when using<
insort
but "well--defined" when usingstd::less<string*>
?