常用的查找算法如下:
find()
find_if()
//
search_n()
search()
find_end()
find_first_of()
adjacent_find()
//
这两种方法通用,对所有容器试用,但是查找效率慢,是线性查找
find() 此复杂度是线性复杂度
find_if() 此复杂度是线性复杂度
注意:
1,如果是已序区间,可以使用 已序区间查找算法(binary_search includes() lower_bound() upper_bound())。
2,关联式容器(set multiset map multimap)有等效的成员函数find() , 此find()复杂度是对数复杂度,速度快
3,,string有等效的成员函数find()
//
#include<iostream>
#include<algorithm>
#include<list>
using namespace std;
int main()
{
list<int> ilist;
for (int i = 1; i <= 8; i++)
{
ilist.insert(ilist.end(), i);
}
for (int i = 1; i <= 8; i++)
{
ilist.insert(ilist.end(), i);
}
for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); iter++)
{
cout << *iter << ' ';
}
cout << endl;
list<int>::iterator pos1;
pos1 = find(ilist.begin(), ilist.end(), 4);
list<int>::iterator pos2;
if (pos1 != ilist.end())
{
pos2 = find(++pos1, ilist.end(), 4);
}
else
cout << "没找到 4!" << endl;
if (pos1 != ilist.end() && pos2 != ilist.end())
{
--pos1;
++pos2;
for (list<int>::iterator iter = pos1; iter != pos2; iter++)
cout << *iter;
}
cout << endl;
//
system("pause");
return 0;
}
#include<iostream>
#include<algorithm>
#include<vector>
//
#include<functional>
using namespace std;
int main()
{
vector<int> ivec;
vector<int>::iterator pos;
for (int i = 1; i <= 9; i++)
ivec.push_back(i);
for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); iter++)
cout << *iter << ' ';
cout << endl;
pos = find_if(ivec.begin(), ivec.end(), bind2nd(greater<int>(), 3)); // 函数对象是 > 3
cout << *pos << endl;
// modulus 取模运算
pos = find_if(ivec.begin(), ivec.end(), not1(bind2nd(modulus<int>(), 3)));
cout << *pos << endl;
//
system("pause");
return 0;
}
//
预定义的函数对象:
negate<type>() equal_to<type>() plus<type>() not_equal_to<type>() minus<type>() less<type>()
multiplies<type>() greater<type>() divides<type>() less_equal<type>() modulus<type>()
greater_equal<type>() logical_not<type>() logical_and<type>() logical_or<type>()
预定义的函数适配器
bindlst(op, value)
bind2nd(op, value)
not1(op)
not2(op)
mem_fun(op)
ptr_fun(op)
已序区间查找算法binary_search()
includes()
lower_bound()
upper_bound()
#include<iostream>
#include<set>
//
using namespace std;
int main()
{
// set 自动排序,是自动平衡的高级的红黑树
set<int> iset;
iset.insert(43);
iset.insert(78);
iset.insert(-1);
iset.insert(124);
for (set<int>::iterator iter = iset.begin(); iter != iset.end(); iter++)
cout << *iter << ' ';
cout << endl;
set<int>::iterator pos;
pos = iset.find(78); // find 是set 的 成员 函数
if (pos != iset.end())
{
cout << "找到了!" << *pos << endl;
}
else
{
cout << "没找到!" << endl;
}
//
system("pause");
return 0;
}
#include<iostream>
#include<string>
//
using namespace std;
int main()
{
string s("AnnaBelle");
string::size_type pos = s.find("Belle");
pos = s.find("bell");
if (pos != string::npos)
cout << "找到了!" << pos << endl;
else
cout << "没找到!" << endl;
//
system("pause");
return 0;
}