所以我的目標是讀入一些數據並按人口排序,但我必須使用可以接受多種數據類型的排序。我被指示使用模板來做到這一點,但每當我將陣列「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
這只是一個問題,其中很多。 –