如何声明对标准算法的引用? [英] How to declare a reference to std algorithm?

查看:47
本文介绍了如何声明对标准算法的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加对 std 算法的引用.如何编辑我的代码以使其正常工作?

I am trying to add a reference to std algorithm. How can I edit my code to make it working?

double f(const std::vector<double> &arr, bool maxElem)
{
    auto me = maxElem ? std::max_element : std::min_element;
    //...
    x = me(arr.begin(), arr.end());
    //...
}

推荐答案

你的函数是模板函数,所以你必须指定模板参数.在这种情况下,使用 std::vector 你需要传递它们 iterators:

Your functions are template functions so you have to specify the template parameter. In this case, using a std::vector you need to pass them iterators:

此外,为了应对函数的不同潜在重载,我们应该强制将它们转换为我们需要的类型(感谢@ChristianHackl):

Also, to cope with different potential overloads of the functions we should cast them to the type we require (thnx to @ChristianHackl):

double f(const std::vector<double>& arr, bool maxElem)
{
    // deduce the iterator parameter types
    using Iterator = decltype(arr.begin());

    // select the overload type
    using Overload = Iterator(*)(Iterator, Iterator);

    auto me = maxElem
        ? static_cast<Overload>(std::max_element<Iterator>)
        : static_cast<Overload>(std::min_element<Iterator>);

    // need to dereference this because `me` returns an iterator
    return *me(arr.begin(), arr.end());
}

还要注意我取消引用来自 me() 的返回值,因为它是一个迭代器(就像一个指针).

Also note I dereference the return value from me() because it is an iterator (like a pointer).

当然,如果您的向量为空,则会取消对无效位置的引用,因此我建议进行检查:

Of course if your vector is empty that will dereference an invalid location so I recommend putting in a check:

double f(const std::vector<double>& arr, bool maxElem)
{
    // Avoid Undefined Behavior
    if(arr.empty())
        throw std::runtime_error("empty vector not allowed");

    // deduce the parameter types
    using Iterator = decltype(arr.begin());

    // select the overload type
    using Overload = Iterator(*)(Iterator, Iterator);

    auto me = maxElem
        ? static_cast<Overload>(std::max_element<Iterator>)
        : static_cast<Overload>(std::min_element<Iterator>);

    // need to dereference this because `me` returns an iterator
    return *me(arr.begin(), arr.end());
}

这篇关于如何声明对标准算法的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆