gpt4 book ai didi

c++ - 重新定义格式参数错误

转载 作者:太空宇宙 更新时间:2023-11-04 13:41:57 24 4
gpt4 key购买 nike

这是我要解决的问题的图像: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();
}

如有任何帮助,我们将不胜感激。

最佳答案

让我们从头开始。此函数不会按照您在代码中定义它的方式被调用。

int main(){
std::vector<Voter> v = readFile("votes.txt");
...
}

您的函数需要三个参数并删除结果。你想在这里返回什么 void (结果是指针参数)或 std::vector< Voter > (希望是右值移动)?

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;
}

关于c++ - 重新定义格式参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27371204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com