在foreach样式循环中设置unsigned int始终为零

Pat*_*.SE 2 c++ c++11

我正在尝试循环一个对象的地图,其中包含unsigned int category我想要设置为枚举值的对象.PlayerToon枚举值等于2.

地图宣言:

std::map<Action, Command> _actionBindings;
Run Code Online (Sandbox Code Playgroud)

设置地图值:

//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";
Run Code Online (Sandbox Code Playgroud)

另一方面,如果我用手动做法明确地替换了循环,我的类别的值确实是'2',如预期的那样:

_actionBindings[Action::MoveLeft].category = Category::PlayerToon;

//Outputs '2'
std::cout << "Category " << _actionBindings[Action::MoveLeft].category << "\n";
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 6

您正在制作地图元素的副本:

for (auto actionPair : _actionBindings)
Run Code Online (Sandbox Code Playgroud)

改为使用引用:

for (auto& actionPair : _actionBindings)
         ^
Run Code Online (Sandbox Code Playgroud)