对于我的uni,我们有一个赋值自动取款机,它将一个.txt文件解析成州和县的两个结构。之后,我们有几种不同的需求来进一步评估数据,例如按家庭收入中位数对州/县进行排序。不幸的是,我需要能够对一组州和一组县执行每个操作。有没有一种有效的方法来重用我的使用州和县的函数,或者我必须重载我的函数并编写更多不需要的代码。下面是一个使用状态的示例函数。
/*********************************************************************
** Function: print_lowest_2015
** Description: prints lowst unenmployment in 2015 from state
** Parameters: states and num
** Pre-Conditions: n/a
** Post-Conditions: n/a
*********************************************************************/
void print_lowest_2015(state* arr, int num) {
int ue;
string name;
ue= arr[0].unemployed_2015;
for (int i = 0; i < num; i++) {
if (arr[i].unemployed_2015 < ue) {
ue = arr[i].unemployed_2015;
name = arr[i].name;
}
}
cout << "State with the lowest 2015 unemployment rate is " << name << " with a value of " << ue << endl;
}
/*********************************************************************
** Function: print_lowest_2015
** Description: prints lowst unenmployment in 2015 from counties
** Parameters: counties and num
** Pre-Conditions: n/a
** Post-Conditions: n/a
*********************************************************************/
void print_lowest_2015(county* arr, int num) {
int ue;
string name;
ue = arr[0].unemployed_2015;
for (int i = 0; i < num; i++) {
if (arr[i].unemployed_2015 < ue) {
ue = arr[i].unemployed_2015;
name = arr[i].name;
}
}
cout << "County with the lowest 2015 unemployment rate is " << name << " with a value of " << ue << endl;
}发布于 2019-01-15 12:05:52
状态无效print_lowest_2015(状态* arr,整数编号){
对数组使用原始指针不是好的c++。所以不用费心去改进它了。这样的代码是在1998年之前编写的。在2019年学习这样的代码是非常危险和无用的。
如果由于某种原因,你不能改变调用代码,下面是你如何以可重用的方式编写函数。
template<class Div>
void print_lowest_2015(Div* arr, int num) {
auto min_div = std::min_element(arr, arr+num, [](Div& s1, Div& s2){
return s1.unemployed_2015 < s2.unemployed_2015;
});
cout << "State with the lowest 2015 unemployment rate is " << min_div->name << " with a value of " << min_div->unemployed_2015 << '\n';
}https://stackoverflow.com/questions/54191867
复制相似问题