mardi 4 juillet 2017

Reset class member

#include <iostream>
#include <map>

using namespace std;

class A
{
public:
    void SetData(std::string key, int value) 
    { 
        if(m_data.find(key) != m_data.end()) m_data.at(key) = value;
        else m_data.insert(std::make_pair(key,value));
    }
    int GetData(std::string key)
    {
        if(m_data.find(key) != m_data.end()) return m_data.at(key);
        return 0;
    }
    void ResetData()
    {
        for(auto item : m_data)
            item.second = 0;
    }
    void ResetData2()
    {
        for(auto it=m_data.begin(); it!=m_data.end(); it++)
            (*it).second = 0;
    }

private:
    std::map<std::string, int> m_data;
};

int main() 
{
    A a;
    a.SetData("KEY1", 10);
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData2();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;

    return 0;
}

Output:

Key1: 10
Key1: 10
Key1: 0

Live demo: http://ift.tt/2ulq25j

What's the difference between the two reset methods here? Resetting the class member std::map<std::string, int> m_data with iterator approach (ResetData2()) works like expected but not range based loop (ResetData())!

Aucun commentaire:

Enregistrer un commentaire