简体   繁体   English

我如何进入一对双 <pair<string,string> ,double&gt;在C ++ 11中

[英]How do I access the double of pair<pair<string,string>,double> in C++11

I am looking to increment the double of a pair when iterating through a map. 我希望在遍历地图时增加一对的两倍。

The map is created as such: 这样创建地图:

typedef pair<string,string> Name;
map<Name,double> paidEmploy;

After I get everything from cin and add it to the map, it will not add an object if the name is already in the map (obviously). 从cin获取所有内容并将其添加到地图后,如果名称已经在地图中(显然),它将不会添加对象。 If the insert then fails, I loop through the map to find the position of the already inserted name. 如果插入失败,我将遍历地图以查找已插入名称的位置。 I then want to access the double of the map to increment by the next amount. 然后,我想访问地图的两倍以增加下一个数量。 How do I access this? 我该如何访问?

Here is what I'm doing so far: 到目前为止,这是我正在做的事情:

map<Name,double> paidEmploy;
string line, fn, ln, date;
double paid;
while(getline(cin, line)){
    istringstream(line) >> date >> fn >> ln >> paid; // assume all lines are correct
    if(paidEmploy.insert(pair<pair<string,string>,double>(pair<string,string>(fn,ln),paid)).second == false){
        for(auto it = paidEmploy.begin(); it != paidEmploy.end(); it++){
            if(it->second.first == fn && it->second.second == ln){
                it->third += paid;
                break;
            }
        }
    }
}

In your case, you may simply do: 就您而言,您可以简单地执行以下操作:

paidEmploy[std::make_pair(fn, ln)] += paid;

Or if really you want to use insert result: 或者,如果真的要使用插入结果:

auto p = paidEmploy.insert(pair<pair<string, string>, double>(std::make_pair(fn, ln), paid));

if (p.second == false) {
    p.first.second += paid;
}
 for(auto it = paidEmploy.begin(); it != paidEmploy.end(); it++){
            if(it->fist.first == fn && it->fist.second == ln){
                it->second += paid;
                break;
            }
        }

you should check it->first not it->second .The map is as follows 您应该检查it->first not it->second 。地图如下

A=>B ie A mapped to B A in your case is a pair<string,string> and B is a double A=>B即映射到B的A在您的情况下是pair<string,string>Bdouble

 it->first //access A ie access the pair<string,string>
 it->second //access B ie access the double

    if(it->first.first == fn && it->first.second == ln){
            it->second += paid;

Also you are searching for the entry in map which destroys the point of having a map in the first place. 另外,您还在地图中搜索条目,这首先破坏了拥有地图的意义。

map::insert gives the inserted position or if the key already exists the position of the affected key (second is false). map :: insert给出插入的位置,或者如果键已经存在,则受影响的键的位置(秒为false)。 Hence there is no need to search again. 因此,无需再次搜索。

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

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