Can input iterators be used where forward iterators are expected?

Viewed 2598

To my knowledge, the hierarchy of iterator categories goes like this:

Random access -> Bi-directional -> Forward -> Input
                                           -> Output

Correct?

I always thought there was a rule, that if an algorithm expects a particular type of iterator, you can provide iterators of categories up the chain, but not down. So I was reading this answer, where ildjarn suggests suggested (then later corrected himself) using std::ifstream with std::istream_iterator and std::search to find data in a in a file. I was about to comment that you can't do that, because search expects Forward iterators, and istream_iterator is an Input iterator. But just to make sure, I tried this:

std::istringstream iss("Elephant hats for sale.");
std::istream_iterator<char> begin(iss), end;

std::string sub("hat");
auto i = std::search(begin, end, sub.begin(), sub.end());

I didn't expect it to compile, but it did. However, the results seem to be useless because if I follow it with this:

while(i != end)
{
    std::cout << *i;
    ++i;
}

There is no output. So, my question is this: Is my compiler in error for allowing my call to search using istream_iterator? Or are there no rules preventing this sort of thing?

1 Answers
Related