C++ 比较字符串,c++;
我有一个问题: 假设有两个C++ 比较字符串,c++;,c++,string,comparison,C++,String,Comparison,我有一个问题: 假设有两个std::strings,我想比较它们,可以选择使用string类的compare()函数,但我也注意到可以使用simple=运算符(即使我没有包含库,这两种情况都是可能的)。 如果可以使用简单的运算符进行比较,有人能解释为什么存在compare()函数吗 顺便说一句,我使用代码::Blocks 13.12 下面是我的代码示例: #include <iostream> #include <string> using std::cin; usin
std::string
s,我想比较它们,可以选择使用string
类的compare()
函数,但我也注意到可以使用simple<>=代码>运算符(即使我没有包含
库,这两种情况都是可能的)。
如果可以使用简单的运算符进行比较,有人能解释为什么存在compare()
函数吗
顺便说一句,我使用代码::Blocks 13.12
下面是我的代码示例:
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::getline;
int main()
{
string temp1, temp2;
cout << "Enter first word: ";
getline (cin,temp1);
cout << "Enter second word: ";
getline (cin,temp2);
cout << "First word: " << temp1 << endl << "Second word: " << temp2 << endl;
if (temp1 > temp2)
{
cout << "One" << endl;
}
if (temp1.compare(temp2) < 0)
{
cout << "Two" << endl;
}
return 0;
}
#包括
#包括
使用std::cin;
使用std::cout;
使用std::endl;
使用std::string;
使用std::getline;
int main()
{
字符串temp1、temp2;
cout.compare()
返回一个整数,它是两个字符串之间差异的度量值
- 返回值
0
表示两个字符串比较相等
- 正值表示比较的字符串更长,或者第一个不匹配的字符更大
- 负值表示比较的字符串较短,或者第一个不匹配的字符较低
操作符==
只返回一个布尔值,指示字符串是否相等
如果你不需要额外的细节,你也可以用==
来回答这个问题
“如果可以使用简单的操作数进行比较,有人能解释为什么存在compare()
函数吗
相对于字符串cat=“cat”;
字符串human=“human”;
有时使用正数、零数或负数可能更有用。auto int f(int,int)->int;
令人不寒而栗。为什么使用尾随返回类型?@rubenvb:还没有人提出使用两种不同的函数声明语法的理由。我猜是“不寒而栗”注释和无效声明意味着您对此处的任何更改都会有情绪上的反应。但我看不到使用两种不同语法的效用,因为只有一种语法就足够了。
auto compare( int a, int b ) -> int { return a - b; }
struct Foo
{
int a;
int b;
int c;
};
auto compare( Foo const& x, Foo const& y )
-> int
{
if( int const r = compare( x.a, y.a ) ) { return r; }
if( int const r = compare( x.b, y.b ) ) { return r; }
return compare( x.c, y.c );
}
string cat = "cat";
string human = "human";
cout << cat.compare(human) << endl;