栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Essential C++ 3.6sub

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Essential C++ 3.6sub

原函数

vector sub_vec(const vector &vec, int val)
{
    vector local_vec(vec);
    sort(local_vec.begin(), local_vec.end());
    vector::iterator iter =
        find_if(local_vec.begin(),
                local_vec.end(),
                bind2nd(greater(), val));
    local_vec.erase(iter, local_vec.end());
    return local_vec;
}

改动后模板函数:

template 
OutputIterator sub_(InputIterator first, InputIterator last,
                    OutputIterator at, const ElemType &val,
                    Comp pred)
{
    OutputIterator at_begin = at;
    while (first != last)
        *at++ = *first++;
    OutputIterator at_end = at;
    sort(at_begin, at_end);
    OutputIterator iter =
        find_if(at_begin,
                at_end,
                bind2nd(pred, val));
    return iter;
}

使用中对于给定待过滤数据,最终返回输出迭代器的终止位置

int main()
{

    const int elem_size = 8;

    int ia[elem_size] = {12, 8, 43, 0, 6, 21, 3, 7};
    vector ivec(ia, ia + elem_size);
    
    int ia2[elem_size];
    vector ivec2(elem_size);

    cout << "normal function:" << endl;
    vector x = sub_vec(ivec, 8);
    for (auto i : x)
        cout << i << ' ';
    cout << endl;

    cout << "template function vector : " << endl;
    vector::iterator iter = sub_(ivec.begin(), ivec.end(),
                                      ivec2.begin(), elem_size,
                                      greater());
    for (auto it = ivec2.begin(); it != iter; ++it)
        cout << *it << ' ';
    cout << endl;

    cout << "template function array : " << endl;
    int *iit = sub_(ia, ia + elem_size,
                    ia2, elem_size, greater());
    for (int ix = 0; ia2 + ix != iit; ++ix)
        cout << *(ia2 + ix) << ' ';
    cout << endl;
    return 0;
}

最终输出结果为:

normal function:
0 3 6 7 8
template function vector :
0 3 6 7 8
template function array :
0 3 6 7 8
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968680.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号