在 C++ 中,可以使用庫中的
sort()函數對結構體數組進行排序,使用
binary_search()` 函數進行查找。這里有一個示例展示了如何實現這兩個操作:
首先,定義一個結構體類型,并包含所需的數據成員:
#include<iostream>
#include<algorithm>
using namespace std;
struct Student {
int id;
string name;
};
接下來,編寫一個比較函數,用于在排序時比較結構體中的特定數據成員。在本例中,我們將根據學生的 ID 進行排序:
bool compareStudents(const Student &a, const Student &b) {
return a.id < b.id;
}
然后,創建一個結構體數組,并添加一些數據:
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;
for (int i = 0; i < n; ++i) {
cout<< students[i].id << ": "<< students[i].name<< endl;
}
if (found) {
cout << "Found student with ID: "<< targetId<< endl;
} else {
cout << "Student not found"<< endl;
}
return 0;
}
完整代碼如下:
#include<iostream>
#include<algorithm>
using namespace std;
struct Student {
int id;
string name;
};
bool compareStudents(const Student &a, const Student &b) {
return a.id < b.id;
}
int main() {
Student students[] = {
{3, "Alice"},
{1, "Bob"},
{4, "Charlie"},
{2, "David"}
};
int n = sizeof(students) / sizeof(Student);
sort(students, students + n, compareStudents);
int targetId = 2;
bool found = binary_search(students, students + n, targetId,
[](const Student &s, int id) { return s.id < id; });
cout << "Sorted array: "<< endl;
for (int i = 0; i < n; ++i) {
cout<< students[i].id << ": "<< students[i].name<< endl;
}
if (found) {
cout << "Found student with ID: "<< targetId<< endl;
} else {
cout << "Student not found"<< endl;
}
return 0;
}
運行此程序,你將看到已排序的學生數組以及查找結果。