首页 > 解决方案 > 遍历 file.txt 并更新地图值

问题描述

我试图更新我的地图,因为我迭代了我的 file.txt 我添加了一些“测试代码”来输出我的值,我得到 125.00(这是我想要的)和 100(我不想要)

我不认为我以正确的方式将其插入地图或以正确的方式检索它。因为我添加之前的值是正确的,当我检索它时,它不是正确的方法

if (accountFile.is_open())
    {
        while (!accountFile.eof())
        {
            (std::getline(accountFile, accounttemp.user, ',') &&
                std::getline(accountFile, accounttemp.trantype, ',') &&
                std::getline(accountFile, (accounttemp.bal)));

            (std::getline(loginFile, logintemp.user, ',') &&
             std::getline(loginFile, (logintemp.pass)));
            cout << logintemp.user << endl;

            //http://www.cplusplus.com/reference/map/map/find/
            // find value given key
            it = balances.find(accounttemp.user);
            if (it != balances.end())
            {
                double holder = 0;
                if (accounttemp.trantype == "D")
                {
                    holder = std::stod(accounttemp.bal) + std::stod(balances.find(accounttemp.user)->second);
                }
                if (accounttemp.trantype == "W")
                {
                    holder = std::stod(accounttemp.bal) - std::stod(balances.find(accounttemp.user)->second);
                }
                stringstream stream;
                stream << fixed << setprecision(2) << holder;
                string s = stream.str();
                accounttemp.bal = s;

                //this is were i added some test code to see my output
                cout << accounttemp.bal << endl;                    
                balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));
                cout << (balances.find(accounttemp.user)->second) << endl;
enter code here
                //out put is 125.00 
                //out put is 100
            }
            else
            {
                balances.insert(std::pair<string, string>(accounttemp.user, (accounttemp.bal)));
            }



        }
    }
    cout << "\n";

标签: c++

解决方案


你有:

        it = balances.find(accounttemp.user);
        if (it != balances.end())
        {

balances仅当包含accounttemp.user元素时才进入块。然后代码有:

            balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));

它什么都不做,因为地图已经包含一个带有该键的元素。请注意,insert不会替换现有元素。最多std::multimap可以插入具有相同键的新元素。但是std::map什么都不会发生。查看以下文档std::map::insert

返回一对由插入元素(或阻止插入的元素)的迭代器和表示插入是否发生的布尔值组成。

我假设它false为您返回,因为没有插入。

修复:改为更新迭代器:

            // instead of:
            // balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));
            it->second = accountemp.bal;

推荐阅读