有人可以解释为什么每当我尝试增加对时没有任何反应?我试过调试它,虽然它进入递增线没有任何反应。
编辑:这是整个功能
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";
}
}
答案 0 :(得分: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";
}
}