這里先介紹find, find_if, find_first_of,三個函數。其余的以后再更新。
一、std::find()
用法:find(first, end, value);
返回區間[first,end)中第一個值等於value的元素位置;若未找到,返回end。函數返回的是迭代器或指針,即位置信息。
參考代碼main(),查找findvalue的值
二、std::find_if()
用法:find_if(first, end, bool pred);
返回區間[first,end)中使一元判斷式pred為true的第一個元素位置;若未找到,返回end。
參考代碼main(),test_find_if();查找第一個被5整除的數,pred寫成bool函數
三、std::find_first_of()
用法:find_first_of(first1, end1, first2, end2);
返回第一個區間迭代器位置,滿足第一個區間[first1,end1)中的元素第一次出現在第二個區間[first2,end2)中。
通俗就是說順序從第一個區間[first1,end1)中取一個元素,在第二個區間中找有沒有相同的元素,如果有就返回第一個區間中元素位置;未找到則繼續
用第一個區間的下一個元素在第二個區間找。
因此只要保證兩個區間內的元素可以==即可,不用管裝元素的容器形式。下面的例子我第一個區間用的vector、而第二個區間是list也是可以的。
參考代碼main(),test_find_first_of();查找vector中第一次出現在list的元素。
代碼示例:
1 bool divbyfive(int x) 2 { 3 return x%5 ? 0 : 1; 4 } 5 6 void test_find_if(vector<int> vec) 7 { 8 vector<int>::iterator vec_it; 9 vec_it=find_if(vec.begin(),vec.end(),divbyfive); 10 if (vec_it!=vec.end()) 11 { 12 cout<<"滿足判斷函數的數為: "<<*vec_it<<"位置在"<<vec_it-vec.begin()<<endl; 13 } 14 else 15 {cout<<"未找到滿足判斷函數的數"<<endl; 16 } 17 return; 18 } 19 20 void test_find_first_of(vector<int> vec) 21 { 22 list<int> list2; 23 for (int i=20;i>5;i--) 24 { 25 list2.push_back(i); 26 } 27 vector<int>::iterator vec_it; 28 vec_it=find_first_of(vec.begin(),vec.end(),list2.begin(),list2.end()); 29 if (vec_it!=vec.end()) 30 { 31 cout<<"第一次出現在第二個容器的元素為: "<<*vec_it<<"位置在: "<<vec_it-vec.begin()<<endl; 32 } 33 else 34 { 35 cout<<"兩個容器沒有相同元素"<<endl; 36 } 37 } 38 39 int main() 40 { 41 vector<int> vec; 42 int findvalue=11; 43 for (int i=1;i<11;i++) 44 { 45 vec.push_back(i); 46 } 47 vector<int>::iterator vec_it; 48 vec_it=find(vec.begin(),vec.end(),findvalue); 49 if (vec_it!=vec.end()) 50 { 51 cout<<findvalue<<" position is "<<distance(vec.begin(),vec_it)<<endl; 52 } 53 else 54 cout<<findvalue<<"is not found"<<endl; 55 56 test_find_if(vec); 57 test_find_first_of(vec); 58 return 0; 59 }
參考:http://www.cnblogs.com/heyonggang/p/3241789.html