Why do I need Forward Iterator to implement my customized std :: search

I am studying the book "Accelerated C ++" from Koenig and Moo.

Exercise 8-2 will ask me to independently implement some templatized functions from <algorithm>and <numeric>, as well as indicate which iterator is performing my implementation.

When I tried to implement it, std::searchI decided that I needed only "introductory" iterators.

Here is my code:

template <class In1, class In2>
In1 search(In1 b, In1 e, In2 b2, In2 e2)
{
    if (b2 != e2) {
        while (b != e) {
            if (*b == *b2) {
                In1 bc = b;
                In2 b2c = b2;
                while (bc != e && b2c != e2 && *bc == *b2c) {
                    ++bc;
                    ++b2c;
                }
                if (b2c == e2)
                    return b;
            }
            ++b;
        }
    }
    return e;
}

However, looking at the implementation std::searchinstalled with my compiler, I see that they use iterators "forward", but I can’t understand why, because there is no need to write, read-only and input iterators meet the requirements.

- , ? "" std::search?

+3
2

. , , .

. , - , - , ; , , , .

(. ):

template <class In1, class In2>
In1 search(In1 b, In1 e, In2 b2, In2 e2)
{
    if (b2 != e2) {
        while (b != e) {
            if (*b == *b2) {
                In1 bc = b;            // copy iterator b
                In2 b2c = b2;
                while (bc != e && b2c != e2 && *bc == *b2c) {
                    ++bc;              // increment the copy of iterator b
                    ++b2c;
                }
                if (b2c == e2)
                    return b;
            }
            ++b;                       // increment the original b
        }
    }
    return e;
}

ForwardIterator - , , , .

( , , ) : a ForwardIterator . , (, , std::forward_list<int>::const_iterator ++ 0x - ).

+6

, , , . (, , , ).

() , , :

// Look at *b and *b2:
        if (*b == *b2) {

            In1 bc = b;
            In2 b2c = b2;

// Now look at the same items again:
            while (bc != e && b2c != e2 && *bc == *b2c) {

(, , ) , .

+4

All Articles