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实现版本:
1 2 3 4 5 6 7 8 9 | 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)。
这样,百万或者千万级的查找就不再话下了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // 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; } |
1 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 | // 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; } |
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记录一次线上问题排查:JDK序列化问题
· 微服务之间有哪些调用方式?
· 记一次SQL隐式转换导致精度丢失问题的排查
· dotnet 9 通过 AppHostRelativeDotNet 指定自定义的运行时路径
· 如何统计不同电话号码的个数?—位图法
· EF Core 10 现已支持 LeftJoin 和 RightJoin 运算符查询了!
· 一个基于 C# Unity 开发的金庸群侠传 3D 版,直呼牛逼!
· 记录一次线上问题排查:JDK序列化问题
· SQL Server 2025 中的改进
· 国内首个「混合推理模型」Qwen3深夜开源,盘点它的N种对接方式!