📅  最后修改于: 2023-12-03 14:39:58.644000             🧑  作者: Mango
在C++中,比较运算符用于判断两个值之间的关系并返回一个布尔值。以下为C++中的比较运算符:
| 运算符 | 描述 | |-------|-------| | == | 相等 | | != | 不等 | | > | 大于 | | < | 小于 | | >= | 大于或等于 | | <= | 小于或等于 |
比较运算符可用于数值变量、字符变量或字符串变量之间的比较。下面是一些示例:
int a = 4, b = 5;
if (a == b) {
cout << "a is equal to b" << endl;
} else if (a > b) {
cout << "a is greater than b" << endl;
} else if (a < b) {
cout << "a is less than b" << endl;
}
char c = 'a', d = 'b';
if (c == d) {
cout << "c is equal to d" << endl;
} else if (c > d) {
cout << "c is greater than d" << endl;
} else if (c < d) {
cout << "c is less than d" << endl;
}
string str1 = "hello", str2 = "world";
if (str1 == str2) {
cout << "str1 is equal to str2" << endl;
} else if (str1 > str2) {
cout << "str1 is greater than str2" << endl;
} else if (str1 < str2) {
cout << "str1 is less than str2" << endl;
}
在某些情况下,需要自定义比较函数来进行特定类型的比较。比如,可以使用自定义比较函数对自定义结构体进行排序。以下是一个自定义比较函数的示例:
struct Person {
string name;
int age;
};
bool compareAge(Person p1, Person p2) {
return p1.age < p2.age;
}
int main() {
vector<Person> people = {{"Alice", 25}, {"Bob", 20}, {"Charlie", 30}};
sort(people.begin(), people.end(), compareAge);
for (Person p : people) {
cout << p.name << " " << p.age << endl;
}
return 0;
}