簡體   English   中英

修改地圖對的值

[英]Modifying value of map pair

有人可以解釋一下為什么每當我嘗試增加對時什么都沒發生嗎? 我嘗試調試它,盡管它到達了遞增行,但沒有任何反應。

編輯:這是整個功能

void VoteCollector::resultsBasedOnAge(std::vector<Voter>& voters)
{
    std::map<int,std::pair<int,int>> ageVoters;
    std::map<int,std::pair<int,int>>::iterator hasAge = ageVoters.begin();


    for(unsigned i = 0; i < voters.size(); i++)
    {
        if(ageVoters.find( voters.at(i).getAge() ) != ageVoters.end() )
        {
            if(voters.at(i).getVote() == "leave")
            {
                hasAge->second.first++;
            }
            else if(voters.at(i).getVote() == "stay")
            {
                hasAge->second.second++;
            }
            hasAge++;
        }
        else
        {
            if(voters.at(i).getVote() == "leave")
            {
                ageVoters.insert(std::make_pair(voters.at(i).getAge(),std::make_pair(1,0)));
            }
            else if(voters.at(i).getVote() == "stay")
            {
                ageVoters.insert(std::make_pair(voters.at(i).getAge(),std::make_pair(0,1)));
            }
            hasAge++;
        }
    }

    for(std::map<int,std::pair<int,int>>::iterator it = ageVoters.begin(); it != ageVoters.end(); it++)
    {
        std::cout << it->first << " years -- " << it->second.first << " leave.\t" << it->second.second << " stay\n";
    }
}

從我的角度來看,您的代碼不起作用,因為您不知道hasAge指向的地方。 您要為其分配std::map::find的結果。

假設您使用的是C ++ 11,代碼也可以簡化:

void VoteCollector::resultsBasedOnAge(const std::vector<Voter>& voters)
{
    std::map<int, std::pair<int, int>> ageVoters;

    for (const auto& v: voters)
    {
        int age = v.getAge();
        const auto& vote = v.getVote();

        auto it = ageVoters.find(age);
        if (it != ageVoters.cend())
        {
            if (vote == "leave")
            {
                ++it->second.first;
            }
            else if (vote == "stay")
            {
                ++it->second.second;
            }
        }
        else
        {
            if (vote == "leave")
            {
                ageVoters.insert(std::make_pair(age, std::make_pair(1, 0)));
            }
            else if (vote == "stay")
            {
                ageVoters.insert(std::make_pair(age, std::make_pair(0, 1)));
            }
        }
    }

    for (const auto& v: voters)
    {
        std::cout << v.first << " years -- "
                  << v.second.first << " leave.\t"
                  << v.second.second << " stay\n";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM