You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.1 KiB

2 years ago
#include <iostream>
#include <algorithm>
struct Person {
std::string name;
int age;
bool operator<(const Person &other) const {
// 自定义的比较规则,按照年龄进行排序
return age < other.age;
}
};
bool compareByName(const Person &p1, const Person &p2) {
// 自定义的比较函数,按照姓名进行排序
return p1.name < p2.name;
}
int main() {
Person people[] = {
{"Alice", 20},
{"Bob", 25},
{"Charlie", 30},
{"David", 35}};
// 使用自定义的比较函数按照姓名排序结构体数组
std::sort(people, people + 4, compareByName);
// 使用lower_bound查找姓名为"Charlie"的人的位置
Person target = {"Charlie", 0};
auto it = std::lower_bound(people, people + 4, target, compareByName);
if (it != people + 4 && it->name == target.name) {
std::cout << "Found Charlie at index " << (it - people) << std::endl;
} else {
std::cout << "Charlie not found" << std::endl;
}
return 0;
}