我有一个问题:
假设有两个std::string
字符串,我想比较它们,有使用string
类的compare()
函数的选项,但我还注意到可以使用简单的< > !=
运算符进行比较(即使我不包括<string>
库)。
请问为什么存在compare()
函数,如果可以使用简单的运算符进行比较呢?
顺便说一句,我使用的是Code::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;
}