stl::set 的一个缺陷

王朝other·作者佚名  2006-02-01
窄屏简体版  字體: |||超大  

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) 就是合法的,并且不会增加创建一个对象的开销

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航