对字符串使用小于比较运算符 [英] Using the less than comparison operator for strings

查看:116
本文介绍了对字符串使用小于比较运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注C ++教程,并研究字符串和+ =,==,!=等运算符的重载,目前它们具有简单的if语句

I'm following a tutorial for C++ and looking at strings and overloading with operators such as +=, ==, != etc, currently have a simple if statement

if(s1 < s2)
    cout << s2 <<endl;
else
  if(s2 < s1)
    cout << s1 << endl;
  else
    cout << "Equal\n";

但是这是如何工作的,程序如何确定哪个字符串大于另一个字符串? 环顾四周,我发现了一个基本的模板整理:

but how does this work, and how does the program decide which string is greater than another? looking around I've found a basic template decleration:

template<class charT, class traits, class Allocator>
  bool operator< ( const basic_string<charT,traits,Allocator>& lhs,
                const basic_string<charT,traits,Allocator>& rhs );

是否定义了<作品?如果是这样,那是什么意思?

does this define how < works? if so, what does mean / do?

以下运算符对字符串也有什么意义? -=和* =

also do the following operators have any meaning for strings? -= and *=

任何建议,我们将不胜感激!

any advice is greatly appreciated!

推荐答案

字符串上的小于运算符对字符串进行字典编排比较.这样,就可以按照字典顺序列出字符串的方式来比较字符串,并普遍适用于具有非字母字符的字符串.

The less-than operator on strings does a lexicographical comparison on the strings. This compares strings in the same way that they would be listed in dictionary order, generalized to work for strings with non-letter characters.

例如:

"a" < "b"
"a" < "ab"
"A" < "a"             (Since A has ASCII value 65; a has a higher ASCII value)
"cat" < "caterpillar"

有关更多信息,请参见 std::lexicographical_compare 算法,小于运算符通常调用该算法.

For more information, look at the std::lexicographical_compare algorithm, which the less-than operator usually invokes.

-=*=一样,这些运算符均未在字符串上定义.定义的唯一算术"运算符是执行字符串连接的++=.

As for -= and *=, neither of these operators are defined on strings. The only "arithmetic" operators defined are + and +=, which perform string concatenation.

希望这会有所帮助!

这篇关于对字符串使用小于比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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