在 C++ 中,可以使用
首先,定义一个结构体类型,并包含所需的数据成员: 接下来,编写一个比较函数,用于在排序时比较结构体中的特定数据成员。在本例中,我们将根据学生的 ID 进行排序: 然后,创建一个结构体数组,并添加一些数据: 现在,使用 接下来,使用 最后,输出排序后的数组以及查找结果: 完整代码如下: 运行此程序,你将看到已排序的学生数组以及查找结果。库中的sort()函数对结构体数组进行排序,使用binary_search()` 函数进行查找。这里有一个示例展示了如何实现这两个操作:#includebool compareStudents(const Student &a, const Student &b) {
return a.id < b>int main() {
Student students[] = {
{3, "Alice"},
{1, "Bob"},
{4, "Charlie"},
{2, "David"}
};
int n = sizeof(students) / sizeof(Student);
sort() 函数对结构体数组进行排序: sort(students, students + n, compareStudents);
binary_search() 函数查找特定元素。为此,请提供要查找的 ID 值: int targetId = 2;
bool found = binary_search(students, students + n, targetId,
[](const Student &s, int id) { return s.id < id> cout << "Sorted array: "<< endl class="hljs-keyword">for (int i = 0; i < n class="hljs-string">": "<< students class="hljs-keyword">if (found) {
cout << "Found student with ID: "<< targetId class="hljs-keyword">else {
cout << "Student not found"<< endl class="hljs-keyword">return 0;
}
#include