STL中常见find()函数的使用---std::find ,set.find, multiset.find, map.find和multimap.find

1.通用std::find 函数

例子1:

 1 // find example  
 2 #include <iostream>  
 3 #include <algorithm>  
 4 #include <vector>  
 5 usingnamespacestd;  
 6    
 7 intmain () {  
 8   intmyints[] = { 10, 20, 30 ,40 };  
 9   int* p;  
10    
11   // pointer to array element:  
12   p = find(myints,myints+4,30);  
13   ++p;  
14   cout << "The element following 30 is " << *p << endl;  
15    
16   vector<int> myvector (myints,myints+4);  
17   vector<int>::iterator it;  
18    
19   // iterator to vector element:  
20   it = find (myvector.begin(), myvector.end(), 30);  
21   ++it;  
22   cout << "The element following 30 is " << *it << endl;  
23    
24   return0;  
25 }  

std::find函数的确有很好的通用性,但是也有很大的缺点,就是算法的效率不高,算法的复杂度为O(n)。无码无真相,让我们看一下 std::find 算法 SGI实现版本:

template
inline _InputIter find(_InputIter __first, _InputIter __last,
const _Tp& __val,
input_iterator_tag)
{
while (__first != __last && !(*__first == __val))
++__first;
return __first;
}

我们可以看到如果找不到,最后find将会返回 last,切记这里的last而非容器的最后一个元素,而是容器的最后。如果想深入了解,请参照《STL源码分析》或者《C++标准程序库》。(*PS,如果仅仅查找一个元素是否存在,用find_if会更明了一些,虽然find和find_if的算法复杂度是相当的。)

2.特定容器的find算法。
        当数据量是百万或者千万级的时候,std::find的O(n)算法就让程序或者客户感到销魂了。
这时候我们可以考虑使用map或者set的算法。是的,这里的find,是map和set的一个成员函数,一个研究ACM的朋友,告诉我map和set中的find算法是用红黑树来实现的。拿起之前的算法的资料,了解到黑红输有良好的最坏情况运行时间,算法复杂度为O(logn)。
这样,百万或者千万级的查找就不再话下了。

// set::find  
#include <iostream>  
#include <set>  
usingnamespacestd;  
   
intmain ()  
{  
  set<int> myset;  
  set<int>::iterator it;  
   
  // set some initial values:  
  for(inti=1; i<=5; i++) myset.insert(i*10);    // set: 10 20 30 40 50  
   
  it=myset.find(20);  
  myset.erase (it);  
  myset.erase (myset.find(40));  
   
  cout << "myset contains:";  
  for(it=myset.begin(); it!=myset.end(); it++)  
    cout << " " << *it;  
  cout << endl;  
   
  return0;  
}  

  

// map::find  
#include <iostream>  
#include <map>  
usingnamespacestd;  
   
intmain ()  
{  
  map<char,int> mymap;  
  map<char,int>::iterator it;  
   
  mymap['a']=50;  
  mymap['b']=100;  
  mymap['c']=150;  
  mymap['d']=200;  
   
  it=mymap.find('b');  
  mymap.erase (it);  
  mymap.erase (mymap.find('d'));  
   
  // print content:  
  cout << "elements in mymap:" << endl;  
  cout << "a => " << mymap.find('a')->second << endl;  
  cout << "c => " << mymap.find('c')->second << endl;  
   
  return0;  
}  

  

猜你喜欢

转载自www.cnblogs.com/shangguanpengfei/p/10483347.html