搜索元素
如果要搜索第一个匹配的元素,你可能要用到:
find(beg,end,value)
find_if(beg,end,op)
第一个形式返回区间[beg,end)中第一个“元素值等于value”的元素的位置;
第二个形式返回区间[beg,end)中令以下一元判断式结果为true的第一个元素:op(elem)
如果没有找到匹配元素,两种都返回end。
关联式容器(set,map,multiset,multimap)提供了一个等效的成员函数find(),拥有对数复杂度,而非线性复杂度。
代码示例:
//find
#include"fuzhu.h"
using namespace std;
int main()
{
list<int> coll;
INSERT_ELEMENTS(coll,1,9);
INSERT_ELEMENTS(coll,1,9);
PRINT_ELEMENTS(coll,"coll:");
list<int>::iterator pos1;
pos1=find(coll.begin(),coll.end(),4);//查找第一次出现4的元素,返回值的是位置
list<int>::iterator pos2;
if(pos1!=coll.end())
{
pos2=find(++pos1,coll.end(),4);
}
if(pos1!=coll.end()&&pos2!=coll.end())
{
for_each(--pos1,++pos2,print);//[beg,end)
cout<<endl;
}
system("pause");
return 0;
}
运行结果:
4 5 6 7 8 9 1 2 3 4
//find_if
#include"fuzhu.h"
using namespace std;
int main()
{
vector<int> coll;
vector<int>::iterator pos;
INSERT_ELEMENTS(coll,1,9);
PRINT_ELEMENTS(coll,"coll: ");
pos=find_if(coll.begin(),coll.end(),bind2nd(greater<int>(),5));//查找第一个大于5的元素,返回的是位置,位置以0开始
cout<<"the "<<distance(coll.begin(),pos)+1<<". elements is the first greater than 5"<<endl;
pos=find_if(coll.begin(),coll.end(),not1(bind2nd(modulus<int>(),3)));//查找第一个可以被3整除的元素,返回的是位置,位置从0开始
cout<<"the "<<distance(coll.begin(),pos)+1<<". elements is the first divsible by 3"<<endl;
system("pause");
return 0;
}
如果要搜寻前n个连续匹配值,你可能要用到:
search_n(beg,end,count,value)
search_n(beg,end,count,value,op)
第一个形式返回区间[beg,end)中第一组“连续count个元素值全等于value”的元素位置;
第二个形式返回区间[beg,end)中第一组“连续count个元素造成以下一元判断式结果为true”的元素位置;
如果没有找到匹配元素,两个都会返回end。
代码示例:
//search_n
#include"fuzhu.h"
using namespace std;
int main()
{
vector<int> coll;
INSERT_ELEMENTS(coll,1,3);
coll.push_back(3);
coll.push_back(3);
coll.push_back(3);
INSERT_ELEMENTS(coll,4,9);
PRINT_ELEMENTS(coll,"coll: ");
vector<int>::iterator pos;
pos=search_n(coll.begin(),coll.end(),4,3);//查找是否存在连续的4个值3的元素 (beg,end,count,value)
if(pos!=coll.end())
{
cout<<"Found "<<"start with "<<distance(coll.begin(),pos)+1<<". element"<<endl;
}
else
{
cout<<"Not Found"<<endl;
}
pos=search_n(coll.begin(),coll.end(),4,3,greater<int>());//查找是否存在连续的4个值大于3的元素 (beg,end,count,value,op)
if(pos!=coll.end())
{
cout<<"Found "<<"start with "<<distance(coll.begin(),pos)+1<<". element"<<endl;
}
else
{
cout<<"Not Found"<<endl;
}
system("pause");
return 0;
}