以下是我必须解决的问题的图片:http://i.imgur.com/WLHntVC.png
我已经完成了相当多的工作,但我确实陷入困境。
我到目前为止的代码是
头文件:voter.h
#include <string>
#include <iostream>
#include <vector>
class Voter {
int id;
std::string votes;
public:
Voter(int id, std::string votes) {
this->id = id;
this->votes = votes;
}
char getVote(int i) {
return votes[i];
}
std::string getVotes() {
return votes;
}
int getID() {
return id;
}
};
Source1.cpp
#include "Voter.h"
#include <fstream>
#include <algorithm>
#include <iomanip>
const int TALLY_MAX = 9;
void readFile(std::string fileName, Voter** v, int& size) {
std::ifstream is(fileName);
Voter** v = nullptr;
int id;
size = 0;
std::string str;
while (!is.eof()){
std::getline(is,str);
size++;
}
v = new Voter*[size];
int i = 0;
while (!is.eof()){
is >> id >> str;
v[i] = new Voter(id, str);
i++;
}
for(int i = 0; i < size; i++)
delete v[i];
delete [] v;
}
void tallyVotes(std::vector<Voter> v, int tally[]) {
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < TALLY_MAX/2; j++) {
int vote = v[i].getVote(j) - 'A';
tally[vote]++;
}
}
}
// sort using a custom function object
struct {
bool operator()(Voter a, Voter b)
{
return a.getID() < b.getID();
}
} customLess;
int main(){
std::vector<Voter> v = readFile("votes.txt");
int tally[TALLY_MAX];
for (int i = 0; i < TALLY_MAX; i++)
tally[i] = 0;
tallyVotes(v, tally);
std::sort(v.begin(), v.end(), customLess);
for (int i = 0; i < v.size(); i++) {
std::cout << std::setfill('0') << std::setw(4) << v[i].getID() << " " << v[i].getVotes() << "\n";
}
std::cout << "\n\nVote Totals\n";
for (int i = 0; i < TALLY_MAX; i++)
std::cout << (char)(i + 'A') << " " << tally[i] << "\n";
//return 0;
std::cin.get();
std::cin.ignore();
}
非常感谢任何帮助。
答案 0 :(得分:0)
让我们从头开始。此函数不会像您在代码中定义它一样被调用。
int main(){
std::vector<Voter> v = readFile("votes.txt");
...
}
您的函数需要三个参数,而是删除结果。你想要返回什么void(结果在指针参数中)或std :: vector&lt;选民&gt; (希望作为左右移动)在这里?
void readFile(std::string fileName, Voter** v, int& size) {
std::ifstream is(fileName);
Voter** v = nullptr;
int id;
size = 0;
std::string str;
while (!is.eof()){
std::getline(is,str);
size++;
}
v = new Voter*[size];
int i = 0;
while (!is.eof()){
is >> id >> str;
v[i] = new Voter(id, str);
i++;
}
for(int i = 0; i < size; i++)
delete v[i];
delete [] v;
}
也许你想要的是:
std::vector< Voter > readFile(const std::string & fileName) {
std::ifstream is(fileName);
std::vector< Voter > v;
int id;
std::string str;
while (is.good()) {
is >> id >> str;
v.push_back( Voter( id, str ) );
}
return v;
}