首页 > 代码库 > std::map, struct pointer 为key
std::map, struct pointer 为key
template < class Key, // map::key_type class T, // map::mapped_type class Compare = less<Key>, // map::key_compare class Alloc = allocator<pair<const Key,T> > // map::allocator_type > class map;
- struct Cell{
- int x;
- int y;
- Cell(int _x,int _y):x(_x),y(_y){}
- };
- struct cmp{
- bool operator()(const Cell* const c1, const Cell * const c2) {
- if(c1->x == c2->x && c1->y == c2->y) return false;
- else return true;
- }
- };
- int main(){
- map<Cell *,int,cmp> mp; // 根据cmp定义的比较函数来比较,如何不相等,则返回true,没有定义<和>
- Cell *c1 = new Cell(1,2);
- Cell *c2 = new Cell(3,4);
- mp[c1] = 1;
- mp[c2] = 1;
- Cell *c3 = new Cell(1,2);
- // mp[c3]=1;
- cout<<mp.size()<<endl;
- if(mp.find(c3) == mp.end()){
- cout<<"can not find it!"<<endl;
- } else {
- cout<<"yes,it exists"<<endl;
- }
- return 0;
- }
默认的key_comp,
key_compare key_comp() const;
Returns a copy of the comparison object used by the container to compare keys.
By default, this is a less object, which returns the same as operator<.
his object determines the order of the elements in the container: it is a function pointer or a function object that takes two arguments of the same type as the element keys, and returns true if the first argument is considered to go before the second in the strict weak ordering it defines, and false otherwise.
Two keys are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).
std::map, struct pointer 为key
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。