当前位置:嗨网首页>书籍在线阅读

12-比较方法和函数

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

F.6 比较方法和函数

string类提供了用于比较2个字符串的方法和函数。下面是方法的原型:

int compare(const basic_string& str) const noexcept;
int compare(size_type pos1, size_type n1,
            const basic_string& str) const;
int compare(size_type pos1, size_type n1,
            const basic_string& str,
size_type pos2, size_type n2) const;
int compare(const charT* s) const;
int compare(size_type pos1, size_type n1, const charT* s) const;
int compare(size_type pos1, size_type n1,
            const charT* s, size_type n2 ) const;

这些方法使用traits::compare()方法,后者是为用于字符串的字符类型定义的。如果根据traits::compare()提供的顺序,第一个字符串位于第二个字符串之前,则第一个方法将返回一个小于0的值;如果这两个字符串相同,则它将返回0;如果第一个字符串位于第二个字符串的后面,则它将返回一个大于0的值。如果较长的字符串的前半部分与较短的字符串相同,则较短的字符串将位于较长的字符串之前。

string s1("bellflower");
string s2("bell");
string s3("cat");
int a13 = s1.compare(s3); // a13 is < 0
int a12 = s1.compare(s2); // a12 is > 0

第二个方法与第一个方法相似,但它进行比较时,只使用第一个字符串中从位置pos1开始的n1个字符。

下面的示例将字符串s1的前4个字符同字符串s2进行比较:

string s1("bellflower");
string s2("bell");
int a2 = s1.compare(0, 4, s2); // a2 is 0

第三个方法与第一个方法相似,但它使用第一个字符串中从pos1位置开始的n1个字符和第二个字符串中从pos2位置开始的n2个字符进行比较。例如,下面的语句将对stout中的out和about中的out进行比较:

string st1("stout boar");
string st2("mad about ewe");
int a3 = st1.compare(2, 3, st2, 6, 3); // a3 is 0

第四个方法与第一个方法相似,但它将一个字符数组而不是string对象作为第二个字符串。

第五和六个方法与第三个方法相似,但将一个字符串数组而不是string对象作为第二个字符串。

非成员比较函数是重载的关系运算符:

operator==()
operator<()
operator<=()
operator>()
operator>=()
operator!=()

每一个运算符都被重载,使之将string对象与string对象进行比较、将string对象与C-风格字符串进行比较、将C-风格字符串与string对象进行比较。它们都是根据compare()方法定义的,因此提供了一种在表示方面更为方便的比较方式。