C++中,結構體是無法進行==,>,<,>=,<=,!=這些操作的,這也帶來了很多不方便的地方,尤其是在使用STL容器的時候,如果我們可以往語句中傳入結構體,一些事情將會變得很簡單。 比如二分尋找,binary_crearch只能對數組進行尋找,如果是結構體數組的話,它會報錯。但很可惜,實際編程中,大部分時候操作對象是結構體數組。 二分尋找結構體數組的程式如下: [cpp] view plain copy #include <iostream> #include <stdio.h> #include <algorithm> using namespace std; struct point { int elem; bool operator==(const point b) const { return this->elem == b.elem; } bool operator!=(const point b) const { return this->elem != b.elem; } bool operator<=(const point b) const { return this->elem <= b.elem; } bool operator<(const point b) const { return this->elem < b.elem; } bool operator>=(const point b) const { return this->elem >= b.elem; } bool operator>(const point b) const { return this->elem > b.elem; } }a[10002],now; int main() { bool flag; int i, n, k; scanf("%d", &n); for (i = 0; i <= n - 1; i++) { scanf("%d", &a[i].elem); } scanf("%d", &k); for (i = 0; i <= k - 1; i++) { scanf("%d", &now.elem); flag = binary_search(a, a + n , now); if (flag == true)