c++ - 修改 map 中包含的类的正确方法是什么?

标签 c++ stl iterator

我有一张类(class) map 。如果我使用迭代器遍历映射,则无法修改类的内容,因为它们必须是常量。无论如何,一个人可以遍历映射(或其他使用迭代器的 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++;
        }
    }

由于 const 限制,这将不起作用。让它按预期工作的正确方法是什么?

谢谢!!

最佳答案

只需使用 map<int, stuff>::iterator而不是 map<int, stuff>::const_iterator

关于c++ - 修改 map 中包含的类的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20669292/

相关文章:

c++ - 如何 “restart”程序

c++ - QT keyPressedEvent太慢?

c++ - 整数到类的映射(模板)

java - Hashmap.keySet()、foreach 和删除

c++ - 从 ‘void* (*)()’ 到 ‘void* (*)(void*)’ [-fpermissive] 的无效转换

c++ - 将信号 (SIGINT) 传播到 C++11 线程

c++:遍历 std::hash_map 的顺序

c++ - 棋盘游戏AI设计: choosing STL data container

java - 抽象 ArrayList<E> 迭代以构建可重用的方法

c++ - 来自 Iterator 定义的 ConstIterator