操作员如何<和>使用指针? [英] How do the operators < and > work with pointers?

查看:121
本文介绍了操作员如何<和>使用指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是为了好玩,我有一个std::listconst char*,每个元素都指向一个以空值结尾的文本字符串,并在其上运行了std::list::sort().碰巧的是,它(没有双关语)没有对字符串进行排序.考虑到它正在处理指针,这是有道理的.

Just for fun, I had a std::list of const char*, each element pointing to a null-terminated text string, and ran a std::list::sort() on it. As it happens, it sort of (no pun intended) did not sort the strings. Considering that it was working on pointers, that makes sense.

根据std::list::sort()文档,默认值)使用元素之间的operator <进行比较.

According to the documentation of std::list::sort(), it (by default) uses the operator < between the elements to compare.

暂时忘记列表,我的实际问题是:这些(>,<,> =,< =)运算符如何在C ++和C中的指针上工作?他们只是比较实际的内存地址吗?

Forgetting about the list for a moment, my actual question is: How do these (>, <, >=, <=) operators work on pointers in C++ and C? Do they simply compare the actual memory addresses?

char* p1 = (char*) 0xDAB0BC47;
char* p2 = (char*) 0xBABEC475;

例如在32位低端系统上,p1> p2是因为0xDAB0BC47> 0xBABEC475?

e.g. on a 32-bit, little-endian system, p1 > p2 because 0xDAB0BC47 > 0xBABEC475?

测试似乎证实了这一点,但是我认为最好将其放在StackOverflow上以备将来参考. C和C ++都做了一些奇怪的东西指向指针,所以您永远不会真正知道...

Testing seems to confirm this, but I thought it'd be good to put it on StackOverflow for future reference. C and C++ both do some weird things to pointers, so you never really know...

推荐答案

在C ++中,您不能使用关系运算符仅比较任何指针.您只能比较两个指向同一数组中元素的指针或两个指向同一对象成员的指针. (当然,您也可以将指针与自身进行比较.)

In C++, you can't compare just any pointers using the relational operators. You can only compare two pointers that point to elements in the same array or two pointers that point to members of the same object. (You can also compare a pointer with itself, of course.)

但是,您可以使用std::less和其他关系比较功能对象来比较任意两个指针.结果是实现定义的,但可以保证总排序.

You can, however, use std::less and the other relational comparison function objects to compare any two pointers. The results are implementation-defined, but it is guaranteed that there is a total ordering.

如果地址空间很平坦,则指针比较很可能只是像比较整数一样比较地址.

If you have a flat address space, it's likely that pointer comparisons just compare addresses as if they are integers.

(我相信C中的规则是相同的,但是没有比较功能对象,但是有人必须确认;我对C的了解不如对C ++的熟悉.)

(I believe the rules are the same in C, without the comparison function objects, but someone will have to confirm that; I'm not nearly as familiar with C as I am with C++.)

这篇关于操作员如何&lt;和&gt;使用指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆