/***********************************************************************
1.投票问题
输入若干候选人,以及投票,格式如下,输出(按输入候选人输入顺序)候选人以及得票,以及
无效票数。
Input:
addCandidate xx1
addCandidate xx2
addCandidate xx3
addCandidate xx4
addCandidate xx5
addCandidate xx6
vote xx2
vote xx2
vote xx3
vote xx3
vote xx4
vote xx6
vote xx7
vote xx1
vote xx1
Output:
xx1 2
xx2 2
xx3 2
xx4 1
xx6 1
1
**********************************************************************/
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <sstream> //istringstream
#include <map>
#include <cstring>
using namespace std;
int main()
{
map<string,int> candidate;
string str;
while(getline(cin,str) && str.size()!=0)
{
str=str.substr(strlen("addCandidate")+1,str.size()-1);
candidate.insert(pair<string,int>(str,0));
}
int size1=candidate.size();//投票前的 候选人数
while(getline(cin,str) && str.size()!=0)
{
str=str.substr(strlen("vote")+1,str.size()-1);
++candidate[str];
}
int size2=candidate.size(); //投票后的 候选人数 可能无效的
int i=0;
map<string,int>::iterator iter=candidate.begin();
while(i < size1)
{
if(iter->second) //有票数的输出
cout<<iter->first<<" "<<iter->second<<endl;
++iter;
i++;
}
int cnt=0;
while(i < size2) //i=size1
{
cnt += iter->second;
i++;
iter++;
}
cout<<cnt<<endl;
return 0;
}
/*************************************************************
2.筷子问题
输入n(筷子数),输出不成对的筷子的长度,无效数据或者没有不成对
的筷子输出-1(没有换行),若有多个,输出一个任意一个即可。
Intput:
7
1 2 2 1 3 3 2
Output:
2
**************************************************************/
#include <iostream>
#include <map>
using namespace std;
int main()
{
int num;
cin>>num;
int *a=new int[num];
int i=0;
map<int,int> imap;
while( i<num && cin>>a[i])
{
++imap[a[i]];
i++;
}
if(i!=num)
{
cout<<-1<<endl;
return 0;
}
for(map<int,int>::iterator iter= imap.begin();iter !=imap.end();++iter)
{
if(iter->second & 1)//为奇数
{
cout<<iter->first<<endl;
return 0;
}
}
cout<<-1<<endl;
delete [] a;
a=NULL;
return 0;
}
本文通过两个具体的编程问题——投票统计和筷子配对问题,展示了如何使用C++标准模板库中的map来解决实际问题。首先介绍了如何统计候选人的投票数量,并处理无效投票;接着讲解了如何找出不成对的筷子长度,提供了完整的代码实现。
1297

被折叠的 条评论
为什么被折叠?



