首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将函数重用于C++中的类似操作

如何将函数重用于C++中的类似操作
EN

Stack Overflow用户
提问于 2019-01-15 10:17:44
回答 1查看 79关注 0票数 0

对于我的uni,我们有一个赋值自动取款机,它将一个.txt文件解析成州和县的两个结构。之后,我们有几种不同的需求来进一步评估数据,例如按家庭收入中位数对州/县进行排序。不幸的是,我需要能够对一组州和一组县执行每个操作。有没有一种有效的方法来重用我的使用州和县的函数,或者我必须重载我的函数并编写更多不需要的代码。下面是一个使用状态的示例函数。

代码语言:javascript
复制
/*********************************************************************
** 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;
    }
EN

回答 1

Stack Overflow用户

发布于 2019-01-15 12:05:52

状态无效print_lowest_2015(状态* arr,整数编号){

对数组使用原始指针不是好的c++。所以不用费心去改进它了。这样的代码是在1998年之前编写的。在2019年学习这样的代码是非常危险和无用的。

如果由于某种原因,你不能改变调用代码,下面是你如何以可重用的方式编写函数。

代码语言:javascript
复制
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://gcc.godbolt.org/z/70oMxs

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54191867

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档