const和非const键有什么区别? [英] What is difference between const and non const key?

查看:187
本文介绍了const和非const键有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两行之间有什么区别?

  map< int,float& map_data; 
map< const int,float> map_data;


解决方案


  • code> int 和 const int 是两种不同的类型。


  • p> std :: map< int,float> std :: map&




std :: map之间的区别< const int,float> ; 和 std :: map< int,float> 是一个程度,类似于之间的区别,例如 std :: map< int,float> std :: map< std :: string,float>



在非 - const ,内部键类型 仍然是非< - code> const int

  std :: map< const int,float> :: key_type => const int 
std :: map< int,float> :: key_type => int

但是,映射键在语义上是不可变的,允许直接访问键(例如,取消引用迭代器,它产生 value_type const ify key_type

  std :: map< const int,float> :: value_type => ; std :: pair< const int,float> 
std :: map< int,float> :: value_type => std :: pair< const int,float>

因此,对于您而言,



虽然:标准正式要求 您的键类型是可复制和可移动的,和一些实施重用地图节点;在这些实现下,尝试使用 const 键将无法工作。


What is the difference between the following two lines?

map<int, float> map_data;
map<const int, float> map_data;

解决方案

  • int and const int are two distinct types.

  • std::map<int, float> and std::map<const int, float> are, similarly, different types.

The difference between std::map<const int, float> and std::map<int, float> is, to a degree, analogous to the difference between, say, std::map<int, float> and std::map<std::string, float>; you get a fresh map type for each.

In the non-const case, the internal key type is still non-const int:

std::map<const int, float>::key_type       => const int
std::map<int, float>::key_type             => int

However, map keys are semantically immutable, and all map operations that allow direct access to keys (for example, dereferencing iterators, which yields value_type) does constify the key_type:

std::map<const int, float>::value_type => std::pair<const int, float>
std::map<int, float>::value_type       => std::pair<const int, float>

So the difference may be largely invisible to you in every way that matters, if your implementation allows it.

That's not always the case, though: the standard officially requires your key type to be copyable and moveable, and some implementations re-use map nodes; under those implementations, attempting to use a const key simply won't work.

这篇关于const和非const键有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆