zoukankan      html  css  js  c++  java
  • 容器 SET part2

     (6) insert   STL中为什么提供这样的set的insert呢?

    这个成员函数存在的目的是为了插入效率的问题。函数参数中的 __position 只是一个提示值,表示在这个位置附近(可前可后)。如果要插入的数据其插入后的位置在 __position 附近的话,使用这个函数可以大大节省插入的时间。反之,如果这两个位置离得很远的话,反而没有用 insert(const value_type& )效率高。
    et类的 insert() 的实现讲起来较复杂,举一个简单的例子来说明吧。

    设有一排好序的整数序列(不妨假定他们存储在一个整型数组中)如下:
    0 1 2 2 5 7 12 34 56 89 100 234

    如果想插入下列数列到上面的数列中,要求插入后的数列仍保持有序:
    15 12 14 20 25 第一个数 15 按照一般的算法(比如从数列开始搜索的方式)插入,得到插入的位置(在 12 之后)。有了这个位置值之后,下一次我们可以把它作为提示值使用,再次插入数据的时候不是从数列的开始处搜索,而是从这个提示位置开始搜索,定位要插入的数据的位置。如果要插入的数据之间比较接近的话(象上面提供的插入数列那样),由于位置比较接近,可以缩短搜索的次数,从而提高插入数据的效率。 还有很重要的一点,就是,参数不同,返回值也是不同的!single element (1)
    pair<iterator,bool>     insert (const value_type& val);
    
    with hint (2)
    iterator                insert (iterator position, const value_type& val);
    
    range (3)
    template <class InputIterator>
      void                  insert (InputIterator first, InputIterator last);
    
    (7)key_compReturns a copy of the comparison object used by the container.

    By default, this is a less object, which returns the same as operator<. 用法:
    std::set<T> myset; std::set<T>::key_compare mycomp = myset.key_comp()  

    (8)自定义比较函数#include <set>
    struct A
    {
       int i;
       int j;
    bool operator<(A const &ref)const
    {  
          return i < ref.i;
    }
    bool operator==(A const &ref)const
    {
        return i == ref.i && j == ref.j;
    }
    };
    int main()
    {
    A val1 = {1, 2};
    A val2 = {2,2};
    std::set<A> my_set;
    my_set.insert(val1);
    my_set.insert(val2);
    } 也就是说要在A中重载和A相关的比较运算符号!那么如果A 不是类或者结构体,就没办法重做比较函数了?

    有办法!

    就是set,不是这种set了!

    struct SetCompare
    {
    bool operator()(const MyPair &it1,const MyPair &it2) const
    {
    if(it1.second >it2.second)
    {
    return true;
    }
    else
    return false;


    }
    };

    typedef set<MyPair,SetCompare> MyPairSetComP;
    MyPairSetComP MyPairContainComp;

    这样就可以!

     typedef set<MyPair,SetCompare>  MyPairSetComP;

     typedef  set<MyPair>  MyPairSet;

    MyPairSetComP MyPairContainComp2=MyPairSetComP(SetCompare());///sucess !

    MyPairSet MyPairContainComp2=MyPairSet(SetCompare());               /// failed!

  • 相关阅读:
    SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-006-处理表单数据(注册、显示用户资料)
    SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)
    SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)
    用CALayer实现聚光灯效果
    用CALayer实现淡入淡出的切换图片效果
    使用CAEmitterLayer实现下雪效果
    使用CAEmitterLayer产生粒子效果
    xcode 删除 Provisioning Profile
    git add相关
    接入淘宝SDK(OneSDK)和支付宝SDK(AlipaySDK)出现 duplicate symbols for architecture i386
  • 原文地址:https://www.cnblogs.com/gaoxianzhi/p/3243097.html
Copyright © 2011-2022 走看看