[英]How can I check values in a C++ map without getting compiler errors in a “const” member function?
I have a member function that compares data in a C++ map.我有一个成员 function 比较 C++ map 中的数据。 I declared the member function as constant:
我将成员 function 声明为常量:
bool operator == (UnitSet otherSet) const;
but as soon as I use myMap["l"] to access and compare values I get compiler errors about myMap being constant.但是一旦我使用 myMap["l"] 访问和比较值,我就会得到关于 myMap 是常量的编译器错误。 Is there a way around this while keeping the const directive?
在保持 const 指令的同时有没有办法解决这个问题?
I know an empty value is created for the "l" key if it didn't exist when I check it, but that won't change the value / behaviour of my UnitSet - maybe I'm trying to be too picky here though and should just drop the "const".我知道如果“l”键在我检查时它不存在,则会为它创建一个空值,但这不会改变我的 UnitSet 的值/行为 - 也许我在这里太挑剔了应该只删除“const”。 What is the good way to go about this?
go 关于这个的好方法是什么?
Thanks.谢谢。
Firstly, you should change your function signature to accept otherSet by const reference, as you have no need to copy it and won't be modifying it:首先,您应该更改您的 function 签名以通过 const 引用接受 otherSet,因为您无需复制它并且不会修改它:
bool operator==(const UnitSet& otherSet) const;
Then, rather than using the non- const
operator[]
, use find()
or begin()
/ !=end()
/ ++
to get const_iterator
s into your map
s for the comparison.然后,不要使用非
const
operator[]
,而是使用find()
或begin()
/ !=end()
/ ++
将const_iterator
放入您的map
进行比较。 As find()
, begin()
and operations on const_iterator
only require const
access to map
, they can be used from your const
member function.由于
find()
, begin()
和const_iterator
上的操作只需要对map
的const
访问,它们可以从您的const
成员 function 中使用。
map<X, Y>::const_iterator i = the_map.find(key);
if (i != the_map.end())
// here, i->first is the key, i->second is the value
else
// key wasn't in the map after all...
std::map
unfortunately doesn't have a const
overload of the []
operator.遗憾的是,
std::map
没有[]
运算符的const
重载。 This is because whenever you access a key that doesn't exist, the map creates an element for it;这是因为每当您访问一个不存在的密钥时,map 都会为其创建一个元素; if the map was
const
, that would be impossible.如果 map 是
const
,那将是不可能的。 Therefore, there's no way to call it with a constant map.因此,没有办法用常数 map 来调用它。 It isn't related to the behavior of your
UnitSet
class.它与
UnitSet
class 的行为无关。
You'll have to use myMap.find(TKey)
to get an iterator to your element, which returns myMap.end()
if it can't find it.您必须使用
myMap.find(TKey)
来获取元素的迭代器,如果找不到则返回myMap.end()
。
Map iterators point to a std::pair
of your key and value, so you need to access the second
member of it to get your value ( first
being the key). Map 迭代器指向您的键和值的
std::pair
,因此您需要访问它的second
成员以获取您的值( first
是键)。
const UnitSet& reference = myMap.find("l")->second;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.