std::map> 分配失败

发布于 2024-07-18 02:30:59 字数 572 浏览 2 评论 0 原文

基本上我有(州,州代码)对,它们是国家的子集 [美国]-> [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>”类型的左侧操作数的运算符

basically i have (state, state code) pairs, that are subsets of country
[USA] -> [VT] -> 32

so i'm using std::map<tstring<std::map<tstring, unsigned int>> but i'm having trouble with assignment of the state code

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
}

error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温折酒 2024-07-25 02:30:59

std::map 上的 operator[] 是非常量,因为如果条目尚不存在,它会创建该条目。 所以你不能以这种方式使用 const_iterator 。 您可以在 const 映射上使用 find(),但这仍然不允许您修改它们的值。

Smashery 是对的,考虑到你有一张地图,你正在以一种奇怪的方式进行第一次查找。 既然你明确地修改了这个东西,这有什么问题吗?

countryList[_T("USA")][_T("MN")] = 5;

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?

countryList[_T("USA")][_T("MN")] = 5;
十年不长 2024-07-25 02:30:59

如果您想在映射中查找元素,可以使用 find 方法:

std::map<tstring, std::map<tstring, unsigned int>::iterator itFind;
itFind = countrylist.find(_T("USA"));
if (itFind != countrylist.end())
{
    // Do what you want with the item you found
    it->second[_T("MN")] = 5;
}

此外,您需要使用迭代器,而不是 const_iterator。 如果使用 const_iterator,则无法修改映射,因为:它是 const!

If you're wanting to find an element in a map, you can use the find method:

std::map<tstring, std::map<tstring, unsigned int>::iterator itFind;
itFind = countrylist.find(_T("USA"));
if (itFind != countrylist.end())
{
    // Do what you want with the item you found
    it->second[_T("MN")] = 5;
}

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文