0
我有一个类的地图。如果我使用迭代器浏览地图,我不能修改类的内容,因为它们需要是const。反正有人可以通过地图(或其他使用迭代器的STL容器)迭代并调用修改每个对象内容的函数吗?修改地图中包含的类的正确方法是什么?
例如:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class stuff
{
public:
void setFoo(int foo);
int getFoo();
private:
int aFoo;
};
void stuff::setFoo(int foo)
{
this->aFoo = foo;
}
int stuff::getFoo()
{
return this->aFoo;
}
int main()
{
stuff myStuff;
stuff myOtherStuff;
myStuff.setFoo(10);
myOtherStuff.setFoo(20);
map<int, stuff> myMap;
myMap.insert(pair<int,stuff>(0, myStuff));
myMap.insert(pair<int,stuff>(5, myOtherStuff));
map<int, stuff>::const_iterator it = myMap.begin();
while (it != myMap.end())
{
it->second.setFoo(it->second.getFoo() * 5); //Expect myStuff.aFoo = 50 and myOtherStuff.aFoo = 100
cout << it->first << " " << it->second.getFoo() << endl;
it++;
}
}
这不会因为常量限制的工作。什么才是正确的方式来使其按预期工作?
谢谢!
,而不是简单的'iterator'? –
正确的方法是当你想修改时不使用const_iterator。 – drescherjm
如果使用C++ x11,那么只需执行'for(auto&it:myMap){it.second.setFoo(...);}' – Brandon