c++ - 强制 std::map 的键类型不是 const

标签 c++ stl map

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

typedef pair<const Key, T> value_type;

是否可以强制 key 类型不是 const ? 我需要在类似

的模板方法中执行此操作
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 ...
}

最佳答案

不,不是。

这是因为 map 根据键执行其内部排序。如果您可以自己修改 key ,无论愿意与否,一切都会变得一团糟。

您应该使用提供的API函数;在使用 one 导致更改键值的情况下(实际上我认为不会),可能会发生适当的内部重新排序。

想想 getter 和 setter,以及它们在为困惑/危险的直接成员访问提供替代方案时的用途。


但是,你可以这样写:

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

std::map 类型别名

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>

关于c++ - 强制 std::map 的键类型不是 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6773734/

相关文章:

haskell - 在 Haskell map 上求和

c++ - 很喜欢选择排序,现在不会排序

c++ - 诸如 `msg(long)` 与候选 `msg(int32_t)` 和 `msg(int64_t)` 等函数的模糊重载

c++ - 当有人尝试在当前 .cpp 或 .h 文件中使用 STL 时显示错误(在 Visual Studio 中)

Javascript 的 "this"指向给 array.map 的 lambda 中的错误对象

java - 什么是 Map.Entry<K,V> 接口(interface)?

c++ - 在单独分配的堆栈上运行函数

c++ - 清除字符串变量内容的不同方法之间有什么区别吗?

c++ - 如何从两个 vector (实数和虚数)中获取复数 vector

c++ - 如何使用 std::sort 对数组中的特定对象进行排序?