所以我的目标是读入一些数据并按人口排序,但我必须使用可以接受多种数据类型的排序。我被指示使用模板来做到这一点,但每当我将阵列“results [i] .pop”传递给我的bubblesort函数时,我收到错误使用模板Bubblesort和结构数组的问题
没有匹配函数调用'bubblesort(std (T *) T bubblesort(T ar [] string &) ) ^ election.cpp:32:3:note:template argument deduction/substitution failed:
election.cpp:106:34:note:can not convert'results [i] .election :: pop (类型“的std :: string {又名性病:: basic_string的}”)为类型“的std :: basic_string的*” 冒泡(结果[I] .pop);
下面的代码:
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <fstream>
#include <stdlib.h>
using namespace std;
struct election {
string party;
string state;
string pop;
string reps;
int ratio;
};
template <typename T>
void bubblesort(T ar[])
{
//Bubblesort
int n = 51;
int swaps = 1;
while(swaps)
{
swaps = 0;
for (int i = 0; i < n - 1; i++)
{
if (ar[i] > ar[i + 1])
{
swap(ar[i],ar[i+1]);
swaps = 1;
}
}
}
//End Bubblesort
}
void delete_chars(string & st, string ch)
{
int i = st.find(ch);
while (i > -1)
{
st.replace(i,1,"");
i = st.find(ch);
}
}
int main()
{
int i = 0;
int n = 51;
election results[n];
int population[n];
int electoralVotes[n];
int ratio[n];
string st;
fstream inData;
//Read in Data from Text File
inData.open("electionresults.txt");
//Print Array as is
cout << "Array Printed As is" << endl;
cout << left << setw(10) << "Party" << setw(20) << "State" << setw(20) << "Population" << setw(15) << "Representatives" << endl;
for (int i = 0; i < n; i++)
{
getline(inData,st);
results[i].party = st.substr(0,1);
results[i].state = st.substr(8,14);
results[i].pop = st.substr(24,10);
results[i].reps = st.substr(40,2);
cout << left << setw(10) << results[i].party << setw(20) << results[i].state << setw(20) << results[i].pop << setw(15) << results[i].reps << endl;
}
//Array Sorted by Population
cout << "Array Sorted By Population" << endl;
cout << endl;
cout << endl;
cout << left << setw(10) << "Party" << setw(20) << "State" << setw(20) << "Population" << setw(15) << "Representatives" << endl;
for(int i = 0; i < n; i++){
bubblesort<string>(results[i].pop);
}
您的模板函数声明为返回'T'。在返回'T'的模板函数中没有'return'语句。此外,没有任何理由可以让一个bubblesort函数返回任何东西。此外,您的bubblesort函数将数组作为参数。当你的main()调用它时,'main()'不会将该数组作为参数传递,而是传递其他内容。整个代码是完全错误的。你需要花更多时间学习模板。这里有太多问题。 –
嗯,这是我第一次使用模板,所以是。我将函数改为void而不是T,但仍然出现相同的错误。 – Nar1y
这只是一个问题,其中很多。 –