zoukankan      html  css  js  c++  java
  • 以RB-tree为底层机制的几个关联式容器

    1、set

    set的键值就是实值,实值就是键值。所以set不可以通过迭代器改变其元素值,它的迭代器都是被定义成const_iterator。

    set是以RB-tree为底层机制的,它的大部分操作都只是转调用RB-tree的操作而已。(默认按照升序排列)

    用法: 

    int  num[]={5,7,3,2,4,4,5};
        set<int>iset(num,num+7);//set会自动排序并删除重复元素:2,3,4,5,7
        int t1=iset.count(2);  //可以用来判断是否有这个元素,有为1,否则为0
        cout<< t1<<endl;
        set<int>::iterator t2=iset.begin();
        t2=iset.find(2);
        if(t2!=iset.end())
            cout<<"find 2"<<endl;
        pair<set<int>::iterator,set<int>::iterator>iter=iset.equal_range(4);
        cout<<* iter.first<<endl;
        cout<< *iter.second<<endl;

    注意:set与vector区别:set是有序且不重复的元素序列,set不可以随机取数,不能有[]操作。

    2、map

    map同时拥有键值和实值,所有元素会自动根据元素的键值排序。第一元素键值第二元素实值。同样map的迭代器不能修改元素的键值,但可以改变实值。它也不允许键值重复。结构如下:

    template<class T1,class T2>
    struct pair{
    typedef  T1 first type;
    typedef T2 second_type;
    T1 first;
    T2 second;
    pair(): first(T1),second((T2())){}
    pair(const T1&a,const T2& b):first(a),second(b){}
    };

    map的用法:

    map<int ,string>name;
        name[3]="c";
        name[2]="b";
        name[1]="a";
        pair<int,string> value(4,"d");
        name.insert(value);
        map<int ,string>::iterator iter_name=name.begin();
        for(;iter_name!=name.end();++iter_name)
            {
            cout<<iter_name->first<<' '<<iter_name->second<<endl;
            cout<<(*iter_name).first<<' '<<(*iter_name).second<<endl;
            }

    输出:

    1 a

    1 a

    2 b

    2 b

    3 c

    3 c

    4 d

    4 d

    3、multiset、multimap

    multiset与set只有一点不同,multiset允许键值重复,它的底层是采用insert_equal() 而非insert_unique()

    multimap与map只有一点不同,multiset允许键值重复,它的底层是采用insert_equal() 而非insert_unique()

  • 相关阅读:
    kotlin实现流读取
    mongo注解详解
    spring 手动注册bean
    mongo 生命周期
    GC类型以及不同类型GC的搭配 1
    GC类型以及不同类型GC的搭配
    Kotlin的高阶函数和常用高阶函数
    通过JVM日志来进行安全点分析
    js中style.display=""无效的解决方法
    Web网页性能管理详解
  • 原文地址:https://www.cnblogs.com/daocaorenblog/p/5309631.html
Copyright © 2011-2022 走看看