【问题标题】:Problem with STL map iterator copyingSTL映射迭代器复制问题
【发布时间】:2011-05-01 02:56:57
【问题描述】:

我有一个要迭代的 STL 映射,但似乎无法使代码正常工作。代码是:

//PowerupInfo is a struct defined in this class's header file
std::map<std::string, PowerupInfo> powerups;

...populate powerups

std::map<std::string, PowerupInfo>::iterator iter;
for (iter = powerups.begin(); iter != powerups.end(); iter++) {
    return iter->second.type ;
}

我得到的错误信息是:

错误:'iter = (((const std::map<:string powerupinfo std::less>, std::allocator > >)((const PowerupList)this)) + 24u)->std::map<_key _tp _compare _alloc>::begin _Key = std::string, _Tp = PowerupInfo, _Compare = std::less<:string>, _Alloc = std::allocator<:pair std::string powerupinfo> >'| 注意:候选者是:std::_Rb_tree_iterator<:pair std::string powerupinfo> >& std::_Rb_tree_iterator<:pair std::string powerupinfo> >::operator=(const std::_Rb_tree_iterator<:pair std::string powerupinfo> >&)|

所以我通常会假设问题与将 iter 设置为它不喜欢的值有关,因为它没有找到“operator=”的匹配项。但为什么?为什么这个任务不起作用?

编辑:

原来方法 WAS const,导致对 powerups 的引用也是 const,从而导致错误。我只是在阅读自己的代码时做得不好。谢谢大家!

【问题讨论】:

  • 你确定iter = powerups.begin() 不是iter = poweruplist.begin() 是你的真正意图吗?

标签: c++ stl map iterator


【解决方案1】:

重新格式化错误代码以使其可读:

error: no match for 'operator=' in 
  'iter = 
    ((
      (const std::map<std::string, PowerupInfo>*)((const PowerupList*)this)
     ) 
      + 24u
    )->std::map<std::string, PowerupInfo>::begin()'

不查看您提供的代码的错误消息。
请剪切并跳过代码。否则没有意义。

【讨论】:

    【解决方案2】:

    您的地图名称是 poweruplist 而不是 powerups(您在 for 循环中使用此名称)。如果这不是错误的原因,那么看起来您是 for 循环位于通过 const 引用接受映射的函数中(或者是类的 const 成员函数)。在这种情况下,您的迭代器类型应该是 const_iterator 而不是 iterator

    【讨论】:

    • 您的意思是您现在没有收到编译器错误,或者是发布问题时的拼写错误?
    • 发布问题时输入错误。 powerups 是 Poweruplist 类的成员,我很困惑:D
    • 将其更改为 const_iterator 可以解决问题,但意味着我无法更改迭代器指向的任何内容,而我确实需要这样做。奇怪的是,据我所知 powerups 不是 const 参考。 powerups 是这个函数是一个方法的同一类的私有成员。有什么想法吗?
    • 成员函数是const吗?或者你可以发布方法的签名吗?
    • @Lewis,如果包含此代码的函数声明为const,那么任何访问的成员也将是const
    猜你喜欢
    • 2011-04-02
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    相关资源
    最近更新 更多