c++ - 'equal'模板函数是如何实现的? (谓词版本)

标签 c++ stl-algorithm

我正在阅读《Accelerated C++》一书,其中一个练习要求我们模拟标题中的“equal”函数,到目前为止,我已经实现了采用三个参数的简单版本,如下所示:

template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){

    while(begin != end){
        if(!(*begin == *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}

第二个版本可以接受第四个参数...

template <class iterType1, class iterType2, class boolPred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){

    while(begin != end){
        if(!pred(*begin, *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}

我的问题是,这是理想的方法吗?或者这两个函数可以合并吗?

最佳答案

第一个版本可以调用第二个版本,传递equal_to对象作为最后一个参数。 或者您可以将其设置为默认参数。 我收回这句话。我实际上无法找到一种为函数模板提供默认参数的方法。我什至无法弄清楚如何在不使用 c++0x 功能(decltype)的情况下重用重载解决方案中的代码。

template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){
    return cequal(begin, end, e, std::equal_to<decltype(*begin)>());
}

关于c++ - 'equal'模板函数是如何实现的? (谓词版本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4731007/

相关文章:

java - 静态类变量存储在内存中的什么位置?

c++ - C++ 中缓慢的 Matlab R2018b TypedArray 数组访问

c++ - 需要对表达式进行解释

c++ - std::includes 实际上是做什么的?

c++ - std::is_sorted 和 strictly less 比较?

c++ - 对 vector C++ 中的上界

c++ - boost::asio::io_service 是否保留处理程序的顺序?

c++ - 如何使 minmax_element 在平局的情况下返回索引最少的元素

c++ - 了解 std::transform 以及如何打败它

c++ - 最后插入是否等同于 std::copy()?