【发布时间】:2016-11-30 03:28:54
【问题描述】:
所以我的目标是读入一些数据并按人口对其进行排序,但我必须使用可以接受多种数据类型的排序。我被指示使用模板来执行此操作,但每次我将数组“results[i].pop”传递给我的冒泡排序函数时,我都会收到错误
没有匹配的函数调用'bubblesort(std::string&)' 冒泡排序(结果[i].pop);” 注:候选人是: 选举.cpp:32:3:注意:模板 T 冒泡排序(T*) T 冒泡排序(T ar[]) ^ 选举.cpp:32:3:注意:模板参数推导/替换失败:
election.cpp:106:34:注意:无法将 'results[i].election::pop'(类型 'std::string {aka std::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语句。此外,无论如何,冒泡排序函数都没有理由返回任何内容。此外,您的冒泡排序函数将数组作为参数。当您的main()调用它时,main()不会将数组作为参数传递,而是传递其他内容。整个代码完全错误。您需要花更多时间研究模板。这里的问题太多了。 -
嗯,这是我第一次使用模板,是的。我将函数更改为 void 而不是 T 但我仍然得到同样的错误。
-
这只是众多问题中的一个。
-
您的模板函数需要
T的数组。您正在传递pop,这不是一个数组。如果你想看看如何组合一个排序模板函数,为什么不通过查看std::sort接口来看看它实际上是如何完成的呢?您忘记将排序 criteria 模板化 - 相反,您将比较硬编码,没有自定义空间。
标签: c++ arrays templates struct