如何設計一個范型算法
// essential c++
向一個容器(比如 vector)中添加數字后,然后隨便輸入待比較的數字( int a ;),求找出在vector中比a大的數字,比a小的數字,和a相等的數字,或者是a的3倍,5倍等之類的數字的集合.
//開始看下面的代碼之前,你是怎么思考的呢?你是不是覺得直接在里面寫個函數比較就是了?或者是其他的呢?
1
#include<iostream>
2
#include <vector>
3
#include <string>
4
using namespace std;
5
/**//*
6
* 單獨寫出相關的函數 如 比較,倍數之類的,后面調用 。
7
* 此處僅寫了小于和大于函數 其他的依次類推。
8
* 注意參數 與指針函數的匹配
9
*/
10
bool less_than(int v1,int v2)
11

{
12
return v1<v2?true:false;
13
}
14
bool greater_than(int v1,int v2)
15

{
16
return v1 > v2 ? true:false;
17
}
18
19
vector<int> filter_ver1(const vector<int> &vec,int filter_value,bool(*pred)(int,int))
20
21
//個人覺得這個函數設置得很好,用到函數指針傳遞相關的函數。注意相關形參的匹配
22

{
23
vector<int> nvec;
24
for(size_t ix = 0;ix != vec.size(); ++ix)
25
if(pred(vec [ix],filter_value)) // 調用相關函數進行操作
26
nvec.push_back(vec[ix]); //滿足結果就保存
27
return nvec;
28
}
29
int main()
30

{
31
int value;
32
vector<int> ivec;
33
cout <<"請輸入數字: "<<endl;
34
while(cin >> value)
35
ivec.push_back(value);
36
cin.clear(); //使輸入流有效
37
int ival;
38
cout<<"請輸入你要比較數字: "<<endl;
39
cin >>ival;
40
vector<int> vec=filter_ver1(ivec,ival ,greater_than); // 函數的調用 傳遞函數名即可
41
vector<int>::iterator it=vec.begin();
42
while(it!= vec.end())
43
cout<<*it++<<" ";
44
cout<<endl;
45
46
system("pause");
47
return 0;
48
}

2

3

4

5


6

7

8

9

10

11



12

13

14

15



16

17

18

19

20

21

22



23

24

25

26

27

28

29

30



31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

posted on 2009-03-30 23:54 彈杯一笑 閱讀(405) 評論(0) 編輯 收藏 引用 所屬分類: c++筆記