How is the 'equal' template function imple

2019-07-12 00:46发布

I am working through the book "Accelerated C++" and one of the exercises require us to emulate the 'equal' function in the header and so far I have implemented the simple version which takes three parameters as follows:

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;
}

and the second version which can accept a fourth parameter...

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;
}

My question is, is this the ideal way to do it? or are these two functions mergable?

3条回答
混吃等死
2楼-- · 2019-07-12 01:13

Those two functions aren't just mergeable, they're almost exactly the same, line for line.

I could expand and do it all for you, but that would be a bit of a spoiler.

查看更多
混吃等死
3楼-- · 2019-07-12 01:15

If you want to merge them, you could provide a default predicate for the last parameter that only calls operator== on the inputs.

edit: an example would be:

template<typename T1, typename T2>
struct eqpred
{
  bool operator(T1 &a, T2 &b) { return a==b; }
}

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

    while(begin != end){
        if(!pred(*begin, *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}
查看更多
别忘想泡老子
4楼-- · 2019-07-12 01:30

The first version can call the second version, passing an equal_to object as the last parameter. Or you can just set that as a default parameter. I take that back. I can't actually figure out a way to have a default argument for a function template. I can't even figure out how to re-use the code in the overload solution without using a c++0x feature(decltype).

template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){
    return cequal(begin, end, e, std::equal_to<decltype(*begin)>());
}
查看更多
登录 后发表回答