In: Computer Science
C++ using vectors.
in the following code, if a user adds duplicate names the votes should be added to only one of the names:
example
display "Enter candidate name: "
input john
display "Enter candidate vote:"
input 10
display "Enter candidate name: "
input john
display "Enter candidate vote:"
input 10
so the output has to be
john with 20 votes.
#include<iostream>
#include<iterator>
#include<string>
#include<algorithm>
#include<array>
#include<ctime>
#include <vector>
#include<bits/stdc++.h>
using namespace std;
int max_element(const vector<int>&stuff)
{
int max_index =0;
for (int i=1; i<stuff.size();++i)
if (stuff[i]>stuff[max_index])
max_index=i;
return max_index;
}
template <typename type>
void show(const vector<type>&stuff)
{
for (int i=0; i<stuff.size(); i++)
cout <<stuff[i]<<' ';
}
int main()
{
vector<string> names;
vector<int> votes;
string name;
int vote;
int size=5;
for (int i=0; i<size;++i)
{
cout<<"enter candidates "<< i+1<<" name: ";
getline(cin, name,'\n');
cout<<"Enter "<<name<< "'s votes ";
cin>>vote;
cin.get();
names.push_back(name);
votes.push_back(vote);
}
for (int k=0; k<size;++k)
{
sort(names.begin(),names.end());
if (names[k-1]==names[k]){
return votes[k];
cout<<"votes "<<votes[k]<<endl;
}
}
int max_index= max_element(votes);
for (int j=0;j<size;++j){
if (votes[j]==votes[max_index])
cout<<"The winners list is bellow "<< names[j]<<endl;
}
return 0;
}
ANS:
#include<iterator>
#include<string>
#include<ctime>
#include <vector>
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int max_element(const vector<int>&stuff)
{
int max_index =0;
for (int i=1; i<stuff.size();++i)
if (stuff[i]>stuff[max_index])
max_index=i;
return max_index;
}
template <typename type>
void show(const vector<type>&stuff)
{
for (int i=0; i<stuff.size(); i++)
cout <<stuff[i]<<' ';
}
int main()
{
vector<string> names;
vector<int> votes;
string name;
int vote;
int size=3;
for (int i=0; i<size;++i)
{
cout<<"enter candidates "<< i+1<<" name: ";
getline(cin, name,'\n');
cout<<"Enter "<<name<< "'s votes ";
cin>>vote;
cin.get();
names.push_back(name);
votes.push_back(vote);
}
for(int i=0;i<size;i++) //Updated checking if same
name exists, Then add their votes all togeather
{
for(int j=i+1;j<size;j++)
{
if(names[i]==names[j])
{
votes[i]+=votes[j];
}
}
}
int max_index= max_element(votes);
for (int j=0;j<size;++j)
{
if (votes[j]==votes[max_index])
cout<<"The winners list is bellow "<< names[j]<<" With Votes="<<votes[j]<<endl;
}
return 0;
}
Comment down for any queries
Please give a thumbs up if you are satisfied with answer
:)