stl::set 的一个缺陷

stl::set 的一个缺陷

 

什么都好,就一点不好:不能仅仅通过 key去查找元素。

 

#include <set >

struct my_struct

{

    int key;

    int value1;

    int value2;

//……..….

//……

    explicit my_struct(int key_) // explicit 禁止将 int 悄悄转化为 my_struct

        : key( key_)

    {

        //....

    }

    struct compare

    {

        bool operator()(const my_struct& l, const my_struct& r) const

        {

            return l.key < r. key;

        }

        bool operator()(const int key, const my_struct& r) const

        {

            return key < r .key;

        }

        bool operator()(const my_struct& l, const int key) const

        {

            return l.key < key;

        }

    };

    struct ptr_compare

    {

        bool operator()(const my_struct* l, const my_struct* r) const

        {

            return l->key < r-> key;

        }

        bool operator()(const int key, const my_struct* r) const

        {

            return key < r ->key;

        }

        bool operator()(const my_struct* l, const int key) const

        {

            return l->key < key;

        }

    };

};

//….

//….

typedef std:: set<my_struct , my_struct:: compare> my_set_type ;

typedef std:: set<my_struct *, my_struct:: ptr_compare> my_ptr_set_type ;

//….

//….

void foo()

{

    my_set_type my_set;

    my_struct   x( 1);

    //....

    my_set. insert(x );

 

    my_struct   y( 100);

    my_set. insert(y );

    //.....

 

    // 错误,不能这样,如果把 explicit my_struct(int key_)

    // 中的 explicit 去掉,这样就可以,但仍然(悄悄地)

    // 增加了创建一个 my_struct 的开销

    my_set_type:: iterator iter2 = my_set. find(100 );

 

    // 只能这样

    my_struct asKey(100 );

    my_set_type:: iterator iter1 = my_set. find(asKey );

    // 或者这样,都增加了创建一个 my_struct 的开销

    my_set_type:: iterator iter3 = my_set. find(my_struct (100));

}

 

void foo2()

{

    my_ptr_set_type my_ptr_set;

    my_struct   x( 1);

    //....

    my_ptr_set. insert(&x );

 

    my_struct   y( 100);

    my_ptr_set. insert(&y );

    //.....

 

    // 错误,不能这样

    my_ptr_set_type:: iterator iter2 = my_ptr_set. find(100 );

 

    // 只能这样

    my_struct asKey(100 );

    my_ptr_set_type:: iterator iter1 = my_ptr_set. find(&asKey );

 

    // 或者这样

    my_ptr_set_type:: iterator iter3 = my_ptr_set. find(&my_struct (100));

}

 

// 如果 std::set::find 是个 template member function:

//    template<typename Key> iterator find(Key key) { ... }

// 那么 my_ptr_set.find(100) 就是合法的,并且不会增加创建一个对象的开销

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值