繁体   English   中英

使用Map插入对象和字符串C ++

[英]Using Map to insert an object and a string C++

我正在读取文件,并且尝试将其添加到如果我在地图中已经找到对象的位置,它将把新对象的值添加到地图中已经找到的对象中。 我不知道如何使用地图的正确语法执行此操作。 这是我所拥有的:

struct ap_pair {
    ap_pair(float tp, float tm) : total_price(tp), total_amount(tm) {};
    ap_pair & operator+=(const ap_pair &);
    float total_price;
    float total_amount;
};


void APC :: compute_total ()
{

    string name;
    map<string, ap_pair> :: iterator my_it;
    float num1, num2, num3;

    while (!fs.eof() )
    {
        fs >> name >> num1 >> num2; //read in file

        ap_pair myobj(num1, num2); //send the weight/count and per unit price ap_pair 

        my_it = mymap.find(name); //returns iterator



       if (my_it != mymap.end()) 
    {                          
    //  myobj+=   //ERROR here. how can I add the new object to the object already in the map?


    }
    else
        mymap.insert(pair<string, ap_pair>(name, myobj));



        if (fs.eof()) break; //makes it so the last line is not repeated

        num3= num1*num2;
        total_amount+=num1;
        total_price+= num3;

    }




}

我正在通过带有if条件的迭代器。 它应该找到具有相同名称的匹配项,但是如何添加已经在地图中与该对象找到的对象的值?

一个std::map迭代器是一对。 第一个元素是键,第二个是值。 如果要将新对象添加到找到的对象中,可以这样进行:

my_it->second += myobj;

->second将为您提供对地图上该位置的对象的引用,然后您只需在其上调用定义的+=运算符即可。

此外,如果您为配对类型创建默认的构造函数(也许将两个字段清零),则可以将代码简化为

while (!fs.eof() )
{
    fs >> name >> num1 >> num2; //read in file
    mymap[name] += ap_pair(num1, num2);

    // ... Rest of the loop...
}

如果运算符[]找不到与name关联的值,它将默认构造一个,然后执行加法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM