在 foreach 样式循环中设置无符号 int 始终为零



我正在尝试循环一个对象的映射,其中包含一个我想设置为枚举值的unsigned int category。玩家卡通枚举值等于 2。

地图声明 :

std::map<Action, Command> _actionBindings;

设置映射值:

//Assign category to value of '2'
for (auto actionPair : _actionBindings)
{
   actionPair.second.category = Category::PlayerToon;  
}
//Outputs '0', expected '2'
std::cout << "Category " << _actionBindings[Action::MoveLeft].category << "n";

另一方面,如果我用手动影响显式替换循环,我的类别的值确实是预期的"2":

_actionBindings[Action::MoveLeft].category = Category::PlayerToon;
//Outputs '2'
std::cout << "Category " << _actionBindings[Action::MoveLeft].category << "n";

您正在在此处复制地图的元素:

for (auto actionPair : _actionBindings)

请改用引用:

for (auto& actionPair : _actionBindings)
         ^

相关内容

最新更新