一、前言——map的查找算法
上次乐鑫的笔试用到了map的查找算法,find,其原型如下所示:
std::map::find
iterator find (const key_type& k);
const_iterator find (const key_type& k) const;
即查找map容器中键值为k的对象,如果找到就返回对应的迭代器,如果没有找到就返回为迭代器end()。
二、stl中常见的查找算法
std::find
1、find,从myvector中查找30:
int myints[] = { 10, 20, 30, 40 };
std::vector<int> myvector (myints,myints+4);
it = find (myvector.begin(), myvector.end(), 30);
if (it != myvector.end())
std::cout << "Element found in myvector: " << *it << '\n';
else
std::cout << "Element not found in myvector\n";
2、find_if() 自定义比较函数
std::find_if():从给定区间中找出满足比较函数的第一个元素;
示例,从myvector中查找能够被30整除的第一个元素:
bool cmpFunction (int i) {
return ((i%30)==0);
}
it = std::find_if (myvector.begin(), myvector.end(), cmpFunction);
std::cout << "first:" << *it <<std::endl;
3、count(),统计元素出现次数
std::count():统计区间中某个元素出现的次数;
std:count_if():count()的自定义比较函数版本
4、search_n() 查询单个元素重复出现的位置
search_n(): find用来查询单个元素,search_n则用来查找区间中重复出现n次的元素;
示例:查询myvector中30连续出现2次的位置:
int myints[]={10,20,30,30,20,10,10,20};
std::vector<int> myvector (myints,myints+8);
it = std::search_n (myvector.begin(), myvector.end(), 2, 30);
参考:常用的STL查找算法