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/