修改地图对的值

问题描述 投票:0回答:1

有人可以解释为什么每当我尝试增加对时没有任何反应?我试过调试它,虽然它进入递增线没有任何反应。

编辑:这是整个功能

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";
    }
}
c++ dictionary stdmap std-pair
1个回答
1
投票

从我看到,你的代码不起作用,因为你的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";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.