码迷,mamicode.com
首页 > 其他好文 > 详细

set容器几个关键函数

时间:2018-10-18 18:08:34      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:lower   ati   mes   amp   自定义   under   假设   public   iter   

set在OI中非常好用,归纳几种常见的功能qwq

#include<iostream>
#include<cstdio>
#include<set>
//set容器常见用法 
using namespace std;
                                                    //用仿函数可以做到自定义排序规则 
class R
{
    public:
    bool operator()(const int &pre,const int &bac)
    {
        return pre>bac;//保证序列前大于后 
    }
};
set<int/*,R*/> s;                                    //去掉注释就会使用仿函数, 
int main()
{
    s.insert(5);
    s.insert(4);
    s.insert(3);
    s.insert(2);
    s.insert(1);
    
    for(set<int>::iterator i=s.begin();i!=s.end();i++)
        cout<<*i<<" ";                                //print 1 2 3 4 5 
        
    //erase
    cout<<endl<<"Erase";                                
    cout<<endl<<s.erase(3)<<endl;                    //删除成功返回1,否则返回0 
    
    for(set<int>::iterator i=s.begin();i!=s.end();i++)
        cout<<*i<<" ";                                //print 1 2 4 5
    
    //uper_bound & lower_bound
    //uper_bound(x):返回 s中 满足大于x 的最小元素 的迭代器 
    //lower_bound(x):返回 s中 满足大于等于x 的最小元素 的迭代器 
    cout<<endl<<"uper_bound & lower_bound";
    cout<<endl<<*s.upper_bound(3);                    //print 4
    
    cout<<endl<<*s.lower_bound(3)<<endl;            //print 4
    
    cout<<endl<<*s.upper_bound(4);                    //print 5
    
    cout<<endl<<*s.lower_bound(4)<<endl;            //print 4
    
    cout<<endl<<(s.lower_bound(6)==s.end())<<endl;    //print 1  当没有一个元素大于等于6时,返回尾迭代器 
    
    //insert
    cout<<endl<<"insert"<<endl;
    s.insert(6); 
    
    for(set<int>::iterator i=s.begin();i!=s.end();i++)
        cout<<*i<<" ";                                //print 1 2 4 5 6
    return 0;
}

值得注意的是,当我们用仿函数改变规则使序列从大到小后,upper_bound和lower_bound的意义就不是注释所描述的那样了。现在这两个函数的功能会很奇怪,下面我用一种适用于任何情况的简单非专业描述来说明这两个函数的功能

lower_bound(x) :

  1. 当容器中存在等于x的元素,返回该元素迭代器
  2. 否则,假设按照容器元素排列规则将x插入容器合适位置,那么返回的是插入后 x下一个(右边)元素的迭代器,若无元素则返回尾迭代器

exa.

  • 6 5 3 2 1 x=4,假设插入后:6 5 4 3 2 1  此时 返回元素3的迭代器
  • # % ^ & * (  ,假设插入¥(假设这是有序序列),# ¥ % ^ & * (  此时 返回元素%的迭代器

upper_bound(x) :

  就是没有1.规则的lower_bound(x) 。。。其他一样

set容器几个关键函数

标签:lower   ati   mes   amp   自定义   under   假设   public   iter   

原文地址:https://www.cnblogs.com/cckk/p/9811777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!