#include<iostream> using namespace std; //compare function for int int IntCmp(void* elem1,void* elem2) { int *ip1=(int*)elem1; int *ip2=(int*)elem2; return *ip1-*ip2; } //compare function for char* int StrCmp(void* elem1,void* elem2) { char* str1 = *(char**)elem1; //直接用char*而不是*(char**)是错的,由于str1将指向字符串地址而非其内容 char* str2 = *(char**)elem2; return strcmp(str1,str2); } void* Isearch(void* key,void* base,int n,int elem_size,int(*cmpfn)(void*,void*)){ for(int i=0;i<n;i++){ void *tmp = (char*)base + i*elem_size; if(cmpfn(key,tmp)==0)return tmp; } return NULL; } void lesson5(){ cout<<"lesson5"<<endl; cout<<"1.generic algorithm/n2.function pointer/n3.data stucture that is simulating c++ class mechanism"<<endl; int array[]={1,2,3,4,5,6}; int size=6; int number=7; int* ifound = (int*)Isearch(&number,array,size,sizeof(int),IntCmp); if(ifound!=NULL) cout<<*ifound<<" is in array"<<endl; else cout<<number<<" is NOT in array."<<endl; char* notes[]={"Ab","F#","B","Gb","p"}; char* favorite_note="Ab"; char** cfound = (char**)Isearch(&favorite_note,notes,5,sizeof(char*),StrCmp); if(cfound!=NULL) cout<<*cfound<<" is in array"<<endl; else cout<<favorite_note<<" is NOT in array."<<endl; } 主要讲了generic algorithm的东西,char**指针是亮点。