曾经的查找
//曾经的查找:顺序查找 #include <iostream> using namespace std; int main( ) { int d[10]={2,7,4,8,12,1,3,5,9,11},i,key,index=-1; cout<<"Input a key you want to search:\n"; cin>>key; for(i=0; i<10; i++) if(key == d[i]) { index = i; break; } if(index >= 0) cout<<"The index of the key is "<<index<<".\n"; else cout<<"Not found.\n"; return 0; }
//曾经的查找:有序表中的二分查找
#include <iostream> using namespace std; int main() { int d[10] = {1,3,9,12,32,41,45,62,75,77}; int low, high,mid,key,index=-1; cin>>key; low=0,high=9; while(low<=high) { mid=(low+high)/2; if(d[mid]==key) { index=mid; break; } else if(d[mid]>key) high=mid-1; else low=mid+1; } if(index >= 0) cout<<"在:"<<index<<".\n"; else cout<<"没有找到.\n"; }
可以这样做
//可以这样做:数组上的find函数 #include <iostream> #include <algorithm> using namespace std; #define SIZE 100 int iarray[SIZE]; int main() { iarray[20] = 50; int* ip = find(iarray, iarray + SIZE, 50); if (ip == iarray + SIZE) cout << "50 not found in array" << endl; else cout << *ip << " found in array" << endl; return 0; }
//可以这样做:利用向量容器、迭代器、算法 #include <iostream> #include <algorithm> #include <vector> using namespace std; vector<int> intVector(100); int main() { intVector[20] = 50; vector<int>::iterator intIter = find(intVector.begin(), intVector.end(), 50); if (intIter != intVector.end()) cout << "Vector contains value " << *intIter << endl; else cout << "Vector does not contain 50" << endl; return 0; }