比较字符串与operator<时,最小字符串是什么?
更具体地说,什么是比任何其他字符串更小(使用<)的字符串?
答案 0 :(得分:9)
空字符串是所有字符串中的“最小”字符串 - 也就是说,它比任何非空字符串都要小。
§21.4.8.4[string :: op<]:
template<class charT, class traits, class Allocator> bool operator< (const basic_string<charT,traits,Allocator>& lhs, const basic_string<charT,traits,Allocator>& rhs) noexcept;
1 返回:
lhs.compare(rhs) < 0
。
§21.4.7.9[string :: compare]:
int compare(const basic_string& str) const noexcept;
1 效果:确定字符串的有效长度
rlen
比较为size()
和str.size()
的最小值。功能 然后通过调用traits::compare(data(), str.data(), rlen)
来比较两个字符串。2 返回:如果结果为非零结果 比较是非零的。否则,返回如下所示的值 表72。
表72 - compare()结果
Condition Return Value size() < str.size() < 0 size() == str.size() 0 size() > str.size() > 0
对于空字符串e
和非空字符串ne
之间的任何比较,rlen
为零,在这种情况下traits::compare()
被指定为返回零 * 。因此,e.compare(ne)
的结果总是小于每个表72的零,e < ne
始终为真。
* 如果“对于[0,n)中的每个i,compare()
为真”,则指定字符特征的X::eq(p[i],q[i])
函数返回零( §21.2.1[char.traits.require],表62);当n == 0
时,范围为空,条件为空。