已序容器查找算法
1.lower_bound() 第一个可能的位置
2.upper_bound() 最后一个可能的位置
3.equal_range() 查找第一个和最后一个可能的位置
***注意:关联式容器有等效的成员函数,性能更佳
#include <iostream>
#include <algorithm>
#include <list>
#include <set>
using namespace std;
int main( int argc, char** argv )
{
list<int> lst;
multiset<int> imset;
//insert
imset.lower_bound(5);
imset.upper_bound(5);
imset.equal_range(5);
for( int i=1; i<10; ++i )
{
lst.push_back(i);
}
for( int i=1; i<10; ++i )
{
lst.push_back(i);
}
lst.push_back(5);
lst.push_back(5);
lst.push_back(5);
lst.push_back(5);
lst.sort();
for(list<int>::const_iterator citr=lst.begin(); citr!=lst.end(); ++citr)
{
cout<<*citr<<' ';
}
cout<<endl;
list<int>::iterator pos1;
list<int>::iterator pos2;
pos1 = lower_bound(lst.begin(), lst.end(), 5);
cout<<"first 5 pos:"<<distance(lst.begin(), pos1)+1<<endl;
pos2 = upper_bound(lst.begin(), lst.end(), 5);
cout<<"大于5的第一个位置:"<<distance(lst.begin(), pos2)+1<<endl;
lst.insert(lower_bound(lst.begin(), lst.end(), 5),5);
lst.insert(upper_bound(lst.begin(), lst.end(), 5),5);
for(list<int>::const_iterator citr=lst.begin(); citr!=lst.end(); ++citr)
{
cout<<*citr<<' ';
}
cout<<endl;
pair<list<int>::iterator, list<int>::iterator> range;
range = equal_range( lst.begin(), lst.end(), 5 );
cout<<distance(lst.begin(),range.first)+1<<' ';
cout<<distance(lst.begin(), range.second)+1<<endl;
return 0;
}