设有3个候选人,12个投票人,程序运行时输入候选人的名字,要求最后输出每个人的得票结果
1.面向过程的程序设计
#include <iostream>
using namespace std;
#include <cstring>
int main()
{
char person[3][10]={"liu","zhang","wang"};
char temp[10];
int i,j;
int votes[3]={0};
for(i=0;i<12;i++)
{
cout<<"Please input the name:"; /*输入候选人姓名*/
cin.getline(temp,10);
for(j=0;j<3;j++)
if(strcmp(temp,person[j])==0)
votes[j]++;
}
for(j=0;j<3;j++)
cout<<person[j]<<":"<<votes[j]<<endl;
return 0;
}
2.面向对象的程序设计(类)
#include <iostream>
using namespace std;
#include <cstring>
class Vote
{
private :
char name [3][10];
int votes[3];
int others;
public:
Vote();
void SetName(int ind,char *name);
char *GetName(int ind);
int& operator[](char *name);
};
Vote::Vote()
{
others=0;
}
char *Vote::GetName(int ind)
{
return this->name[ind];
}
int& Vote::operator[](char *name)
{
for(int j=0; j<3; j++)
if(strcmp(this->name[j],name)==0)
return votes[j];
return others;
}
void Vote::SetName(int ind,char *name)
{
strcpy(this->name[ind],name);
votes[ind]=0;
}
int main()
{
char name[3][10]= {"liu","zhang","wang"};
char temp[10];
int i,j;
Vote person;
for(i=0; i<3; i++)
person.SetName(i,name[i]);
for(i=0; i<4; i++)
{
cout<<"Please input the name:"; /*输入候选人姓名*/
cin.getline(temp,10);
person[temp]++;
}
for(j=0; j<3; j++)
cout<<person.GetName(j)<<":"<<person[person.GetName(j)]<<endl;
return 0;
}
3.<map>映射的应用
#include <iostream>
using namespace std;
#include <cstring>
#include <map>
int main()
{
string name[3]= {"liu","zhang","wang"};
string temp;
int i;
// Vote person;
map<string,int> person;
// for(i=0; i<3; i++)
// person[name[i]]=0;
for(i=0; i<4; i++)
{
cout<<"Please input the name:"; /*输入候选人姓名*/
cin>>temp;
person[temp]++;
}
for(i=0; i<3; i++)
cout<<name[i]<<":"<< person[name[i]]<<endl;
// 遍历容器输出实际保存的数据
// for(map<string,int>::iterator iter=person.begin(); iter!=person.end(); ++iter)
// cout<<iter->first<<":"<<iter->second<<endl;
return 0;
}
4.拓展增加--
1. 修改类Vote实现候选人的个数是可变的
2. 将类Vote的成员函数Vote::operator[]的查找方法改为二分法查找

本文介绍了一个简单的投票程序设计案例,包括面向过程与面向对象两种方法,并使用C++标准库中的map来实现候选人的投票计数。
950

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



