std::map> 分配失败
基本上我有(州,州代码)对,它们是国家的子集 [美国]-> [VT]-> 32
所以我使用 std::map
但我在分配状态代码时遇到问题
for(std::map<tstring, std::map<tstring, unsigned int>>::const_iterator it = countrylist.begin(); it != countrylist.end(); ++it)
{
foundCountry = !it->first.compare(_T("USA")); //find USA
if(foundCountry) it->second[_T("MN")] = 5; //Assignment fails
}
错误 C2678:二进制“[”:找不到采用“const std::map<_Kty,_Ty>”类型的左侧操作数的运算符
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::map 上的 operator[] 是非常量,因为如果条目尚不存在,它会创建该条目。 所以你不能以这种方式使用 const_iterator 。 您可以在 const 映射上使用 find(),但这仍然不允许您修改它们的值。
Smashery 是对的,考虑到你有一张地图,你正在以一种奇怪的方式进行第一次查找。 既然你明确地修改了这个东西,这有什么问题吗?
operator[] on std::map is non-const, because it creates the entry if it doesn't already exist. So you can't use a const_iterator in this way. You can use find() on const maps, but that still won't let you modify their values.
And Smashery is right, you're doing the first lookup in a strange way considering that you have a map. Since you're clearly modifying the thing, what's wrong with this?
如果您想在映射中查找元素,可以使用 find 方法:
此外,您需要使用迭代器,而不是 const_iterator。 如果使用 const_iterator,则无法修改映射,因为:它是 const!
If you're wanting to find an element in a map, you can use the find method:
Also, you'll want to be using iterator, and not const_iterator. You can't modify the map if you use a const_iterator, because: it's const!