关联容器set, multiset

set, multiset, map, multimap

  • 内部元素有序排列,新元素插入的位置取决于它的值,查找速度快。
  • 除了各容器都有的函数外,还支持以下成员函数。
    • find:查找等于某个值的元素(x<y和y<x同时不成立即为相等)
    • lower_bound:查找某个下界
    • upper_bound:查找某个上界
    • equal_range:同时查找上界和下界
    • count:计算等于某个值的元素个数(x<y和y<x同时不成立即为相等)
    • insert:用以插入一个元素或一个区间

multiset

template<class  Key, class  Pred = less<Key>>, class A=allocator<Key> >

class multiset { …. };

  • Pred 决定了类multiset中比大小的原则,multiset运行过程中,比较两个元素x、y的大小的做法,就是生成一个Pred类型的变量,假定为op,若表达式op(x,y)返回值为true,则x比y小。op一般为函数指针或者函数对象。
  • Pred的缺省类型是less<Key>。
  • less 模板的定义:

template<class T>

struct  less : public binary_function<T, T,bool>

{bool  operator()(const T&x , const T&y){ return x<y ;} const; };

//less模板是靠 < 来比较大小的。

 

 

set

template <class  Key , class  Pred = less<Key>, class A = allocator<Key> >

class set{ … }

插入set中已有的元素时,忽略插入。

 

multiset实验代码:

#include <iostream>
#include <set>

using namespace std;

template <class T>
void Print(T first, T last)
{
    for (; first != last; first++)
    {
        cout << *(first) << " ";
    }
    cout << endl;
}
class A
{
private:
    int n;
public:
    A(int _n) :n(_n) {};
    friend bool operator<(const A & a1, const A& a2)
    {
        return a1.n < a2.n;    
    }
    friend ostream & operator<<(ostream & o,const A &a)
    {
        o << a.n;
        return o;
    }
    friend class Myclass;
};
struct Myclass
{
    bool operator()(const A & a1, const A & a2)
    {
        return (a1.n % 10 < a2.n % 10);
    }
};

typedef multiset<A> Mset1;
typedef multiset<A, Myclass> Mset2;//重新定义排序

int main()
{
    const int size = 6;
    A a[size] = { 1, 12, 9, 20, 89 ,78};
    Mset1 m1;
    m1.insert(a, a + size);
    Print(m1.begin(), m1.end());
    m1.insert(20);
    cout << "inserted the number:20" << endl;
    Print(m1.begin(),m1.end());
    Mset1::iterator it;
    it = m1.find(20);
    m1.erase(it);
    cout << "deleted the number:20" << endl;
    Print(m1.begin(), m1.end());
    Mset2 m2;
    m2.insert(m1.begin(), m1.end());
    cout << "the multiset m2 is :" << endl;
    Print(m2.begin(), m2.end());
    return 0;
}

 

运行结果:

  

set实验代码:

#include <iostream>
#include <set>
using namespace std;
int main() {
typedef set<int>::iterator IT;
int a[5] = { 3,4,6,1,2 };
set<int> st(a,a+5); // st里是 1 2 3 4 6
pair< IT,bool> result;
result = st.insert(5); // st变成 1 2 3 4 5 6
if( result.second ) //插入成功则输出被插入元素
cout << * result.first << " inserted" << endl; //输出: 5 inserted
if( st.insert(5).second ) cout << * result.first << endl;
else
cout << * result.first << " already exists" << endl; //输出 5 already exists
pair<IT,IT> bounds = st.equal_range(4);
cout << * bounds.first << "," << * bounds.second ; //输出:4,5
return 0;
}

 

 参考链接:

https://www.coursera.org/learn/cpp-chengxu-sheji

posted @ 2016-07-09 10:57  helloforworld  阅读(243)  评论(0编辑  收藏  举报