std::string comparison
分类:技术
众所周知,char 类型是独立于 unsigned char 和 signed char 之外的一种实现相关类型,这着实带来了不少麻烦。
std::string a = "Hello";
std::string b = "世界"; // UTF-8 或者 GBK 皆可
那么请问,a[0] < b[0] 是什么结果?OK,那么 a < b 呢?
当然,貌似在开篇头一句就已经被我剧透的情况下作出错误的回答还是蛮困难的。没错,无论是 GBK 还是 UTF-8 存储,答案都应该是:
a[0] < b[0]与实现相关。在我的 Windows 7 32-bit 和 Arch Linux 64-bit 上,都是falsea < b永远为true
前者很好理解,因为实质是两个 char 在比较,所以谁大谁小还得看 char 到底是无符号的还是有符号的。而后者为什么肯定是 true 呢?
尽管 std::string 是 std::basic_string 在字符类型为 char 时的特化,但 C++ 标准中明确规定:
The two-argument members
eqandltshall be defined identically to the built-in operators == and < for typeunsigned char.
也算是 C++ 造福人类的某种方式吧。
以上。