【问题标题】:How do I access the double of pair<pair<string,string>,double> in C++11如何在 C++11 中访问 pair<pair<string,string>,double> 的双精度
【发布时间】:2015-07-03 19:42:27
【问题描述】:

我希望在遍历地图时增加一对的双倍。

地图是这样创建的:

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

在我从 cin 获取所有内容并将其添加到地图后,如果名称已经在地图中(显然),它将不会添加对象。如果插入失败,我会遍历地图以查找已插入名称的位置。然后我想访问地图的双倍以增加下一个数量。我如何访问它?

这是我目前正在做的事情:

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;
            }
        }
    }
}

【问题讨论】:

    标签: c++ c++11 dictionary iterator


    【解决方案1】:

    在你的情况下,你可以简单地这样做:

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

    或者如果你真的想使用插入结果:

    auto p = paidEmploy.insert(pair<pair<string, string>, double>(std::make_pair(fn, ln), paid));
    
    if (p.second == false) {
        p.first.second += paid;
    }
    

    【讨论】:

    • 更简洁:paidEmploy[{fn, ln}] += paid。 (虽然有些人可能认为这有点太迟钝了。)
    【解决方案2】:
     for(auto it = paidEmploy.begin(); it != paidEmploy.end(); it++){
                if(it->fist.first == fn && it->fist.second == ln){
                    it->second += paid;
                    break;
                }
            }
    

    【讨论】:

      【解决方案3】:

      map::insert 给出插入的位置,或者如果键已经存在,则给出受影响键的位置(第二个为假)。因此无需再次搜索。

      【讨论】:

        【解决方案4】:

        你应该检查it-&gt;first not it-&gt;second。地图如下

        A=&gt;B 即 A 映射到 B A 在您的情况下是 pair&lt;string,string&gt;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;
        

        此外,您正在地图中搜索条目,这首先破坏了拥有地图的意义。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多