强制键类型的一个std :: map不是const [英] force key type of a std::map not to be const

查看:176
本文介绍了强制键类型的一个std :: map不是const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++引用告诉我们std :: map

  typedef pair< const Key,T& value_type; 

是否可以强制键类型不是const?
我需要在一个模板方法中这样做

  template< class T& // T代表一个地图(std :: map,boost :: unordered_map或者其他..)
void foo(const T& m)
{
typename T :: value_type: :first_type x;
x = 0; //错误,因为x是const ...
}


解决方案>

不,不是。



这是因为map基于键执行其内部排序。



你应该使用提供的API函数;如果你可以自己修改密钥,其中使用一个结果改变一个键值(实际上我不认为任何做),适当的内部重新排序可能发生。



想想






但是,你可以写下这个:

  template< class T> 
void foo(const T& m)
{
typename T :: key_type x;
x = 0;
}






std :: map type aliases



  key_type Key 
mapped_type T
value_type pair< const Key,T>
key_compare比较
value_compare用于比较元素的嵌套类
allocator_type分配器
引用Allocator :: reference
const_reference Allocator :: const_reference
迭代器双向迭代器
const_iterator常量双向迭代器
size_type无符号整数类型(通常与size_t相同)
difference_type有符号整数类型(通常与ptrdiff_t相同)
指针Allocator :: pointer
const_pointer Allocator :: const_pointer
reverse_iterator reverse_iterator< iterator>
const_reverse_iterator reverse_iterator< const_iterator>


C++ references tells us for a std::map

typedef pair<const Key, T> value_type;

Is it possible to force the Key Type not to be const ? I need to do this in a template method like

template<class T> // T represent a map in general (std::map, boost::unordered_map or whatever..)
void foo(const T& m)
{
  typename T::value_type::first_type x;
  x=0; // Wrong because x is const ...
}

解决方案

No, it's not.

This is because map performs its internal ordering based on key. If you could modify the key yourself, willy-nilly, all hell would break loose.

You should use the provided API functions; where the use of one results in changing a Key value (actually I don't think that any do), the appropriate internal re-ordering may take place.

Think of getters and setters, and their use in providing an alternative to messy/dangerous direct member access.


However, you could write this:

template<class T>
void foo(const T& m)
{
   typename T::key_type x;
   x = 0;
}


std::map type aliases

key_type                Key
mapped_type             T
value_type              pair<const Key,T>
key_compare             Compare
value_compare           Nested class to compare elements
allocator_type          Allocator
reference               Allocator::reference
const_reference         Allocator::const_reference
iterator                Bidirectional iterator
const_iterator          Constant bidirectional iterator
size_type               Unsigned integral type (usually same as size_t)
difference_type         Signed integral type (usually same as ptrdiff_t)
pointer                 Allocator::pointer
const_pointer           Allocator::const_pointer
reverse_iterator        reverse_iterator<iterator>
const_reverse_iterator  reverse_iterator<const_iterator>

这篇关于强制键类型的一个std :: map不是const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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