7. 7Ch動董ng 10: Thu畉t to叩n t畛ng qu叩t
template <typename COMP>
int* find_elem(int* first, int* last, int k, COMP comp) {
while (first != last && !comp(*first, k))
++first;
return first;
}
bool is_greater(int a, int b) { return a > b; }
bool is_less(int a, int b) { return a < b; }
bool is_equal(int a, int b) { return a == b;}
void main() {
int a[] = { 1, 3, 5, 2, 7, 9, 6 };
int* alast = a+7;
int* p1 = find_elem(a,alast,4,is_greater);
int* p2 = find_elem(a,alast,4,is_less);
int* p3 = find_elem(a,alast,4,is_equal);
if (p1 != alast) cout << "First number > 4 is " << *p1;
if (p2 != alast) cout << "First number < 4 is " << *p2;
if (p3 != alast) cout << "First number = 4 is at index "
<< p3 - a;
char c; cin >> c;
}
8. 8Ch動董ng 10: Thu畉t to叩n t畛ng qu叩t
Tham s畛 khu担n m畉u cho ph辿p to叩n
C坦 th畛 l m畛t hm, v鱈 d畛
bool is_greater(int a, int b){ return a > b; }
bool is_less(int a, int b) { return a < b; }
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
...
Ho畉c t畛t h董n h畉t l m畛t 畛i t動畛ng thu畛c m畛t l畛p c坦 h畛 tr畛 (n畉p
ch畛ng) to叩n t畛 g畛i hm => 畛i t動畛ng hm, v鱈 d畛
struct Greater {
bool operator()(int a, int b) { return a > b; }
};
struct Less {
bool operator()(int a, int b) { return a < b; }
};
struct Add {
int operator()(int a, int b) { return a + b; }
};
...