首页 > 代码库 > 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;

  1. struct Cell{
  2. int x;
  3. int y;
  4. Cell(int _x,int _y):x(_x),y(_y){}
  5. };
  6. struct cmp{
  7. bool operator()(const Cell* const c1, const Cell * const c2) {
  8. if(c1->x == c2->x && c1->y == c2->y) return false;
  9. else return true;
  10. }
  11. };
  12. int main(){
  13. map<Cell *,int,cmp> mp; // 根据cmp定义的比较函数来比较,如何不相等,则返回true,没有定义<和>
  14. Cell *c1 = new Cell(1,2);
  15. Cell *c2 = new Cell(3,4);
  16. mp[c1] = 1;
  17. mp[c2] = 1;
  18. Cell *c3 = new Cell(1,2);
  19. // mp[c3]=1;
  20. cout<<mp.size()<<endl;
  21. if(mp.find(c3) == mp.end()){
  22. cout<<"can not find it!"<<endl;
  23. } else {
  24. cout<<"yes,it exists"<<endl;
  25. }
  26. return 0;
  27. }

默认的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