STL-MAP使用方法总结

template <class Key, class T, class Compare, class Alloc = alloc>
class map 
{
public:
// typedefs:
	typedef Key key_type;
	typedef T data_type;
	typedef T mapped_type;
	typedef pair<const Key, T> value_type;
	typedef Compare key_compare;
private:
	typedef rb_tree<key_type, value_type, select1st<value_type>, key_compare, Alloc> rep_type;
	rep_type t;  // red-black tree representing map
public:
	typedef typename rep_type::pointer pointer;
	typedef typename rep_type::const_pointer const_pointer;
	typedef typename rep_type::reference reference;
	typedef typename rep_type::const_reference const_reference;
	typedef typename rep_type::iterator iterator;
	typedef typename rep_type::const_iterator const_iterator;
	typedef typename rep_type::reverse_iterator reverse_iterator;
	typedef typename rep_type::const_reverse_iterator const_reverse_iterator;
	typedef typename rep_type::size_type size_type;
	typedef typename rep_type::difference_type difference_type;
	........
};  
如果我们遍历map的红黑树,以其输出顺序为数据项安排顺序号,那么“使比较函数为真的数据项”将靠前。

在选择map的关键字时,注意以下两点,同时这两点也是改错的方法: a) 关键字明确定义“<”比较操作符 b) 没有“<”比较操作符,自定义仿函数替代第三个参数Compare,该仿函数实现“()”操作符,提供比较功能。插入时各节点顺序以该仿函数为纲。

std::map容器不同的关键字问题
1.以std::pair<int, int>为关键字
该关键字没有明确的"<"比较操作符,我们应当为其编写编写比较函数:
struct comp
{
       typedef std::pair<int, int> value_type;
       bool operator () (const value_type & ls, const value_type &rs)
       {
              return ls.first < rs.first || (ls.first == rs.first && ls.second < rs.second);
       }
};
所以该关键字类型的map使用方法可如下表示:
声明变量:std::map<std::pair<int, int>, int, comp> res;
查找方法:std::map<std::pair<int, int>, int, comp>::iterator it = res.find(std::make_pair(121,331));

insert函数返回值问题
在map容器中插入数据有很多函数可用,这里只讨论最普通的insert操作,在STL中它是这样定义的。

pair<iterator, bool> insert(const value_type& x);

insert函数的返回值是一个迭代器和布尔值的键值对,迭代器指向map中具有该值的元素,布尔值表示是否插入成功。map容器不允许键值重复,在执行插入操作后,可以凭借该返回值获取操作结果。

布尔值为true,表示插入成功,则迭代器为新插入值在map中的位置;
布尔值为false,表示插入失败(已经存在该值),迭代器为原有值在map中的位置。

map查找方法
1.根据关键字查找
2.根据值查找

1.根据关键字查找
2.根据值查找
std::map定义的查找方法,都是根据关键字查找。如果需要根据值进行查找,有两种方法:a)自己写遍历函数,逐次比较;b)使用std::find_if函数,使用该方法需定义用来比较的仿函数。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值