Essential C++ 3.6sub

Essential C++ 3.6sub,第1张

原函数

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

改动后模板函数:

template <typename InputIterator, typename OutputIterator,
          typename ElemType, typename Comp>
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<int> ivec(ia, ia + elem_size);
    
    int ia2[elem_size];
    vector<int> ivec2(elem_size);

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

    cout << "template function vector : " << endl;
    vector<int>::iterator iter = sub_(ivec.begin(), ivec.end(),
                                      ivec2.begin(), elem_size,
                                      greater<int>());
    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<int>());
    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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1352555.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-14
下一篇 2022-06-14

发表评论

登录后才能评论

评论列表(0条)

保存