c++中std::map key使用智能指针笔记

#include <cstring>
#include <cstdio>
#include<map>
#include<memory>
#include <iostream>
#include<string>
using namespace std;

struct Comparator : public std::binary_function<shared_ptr<string>, shared_ptr<string>, bool>{
  bool operator()(shared_ptr<string> const & left, shared_ptr<string> const& right) const{
    return left->compare(*right)<0;//The comparer should return whether the first string should go before the second string. Either return x.compare(y) < 0
  }
};
int main(){
  map<shared_ptr<string>,int,Comparator> test;
  test.insert(make_pair(make_shared<string>("test1"),123));
  test.insert(make_pair(make_shared<string>("test2"),234));
  test.insert(make_pair(make_shared<string>("test3"),369));
  test.insert(make_pair(make_shared<string>("test4"),258));
  //test.insert(make_pair(make_shared<string>("test4"),99));

  //  cout<<"test:"<<test[make_shared<string>("test5")]<<endl;//carefull
  cout<<"size:"<<test.size()<<endl;
  shared_ptr<string> key=make_shared<string>("test4");
  int count = test.count(key);
  if(count==1){
      map<shared_ptr<string>,int,Comparator>::iterator it = test.find(key);
      cout<<"value:"<<it->second<<endl;
    }

  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值