return type amgiguity

I have just been learning about the algorithms in c++ and I am currently looking at 'mismatch'

I read that the return type is a pair or iterators with three conditions for setting the iterators use in the return value.

case 1: a mismatch found: both iterators point to the corresponding values in their respective ranges. No problem here.

case 2: no mismatch is found: iterator1 points to end() and iterator two points to the corresponding position in its range. No problem here.

case 3: all data elements are mismatched, both pointers point to first1, first2 (as defined in the prototype (i.e, the first value in the range).

If for example you used:

 
auto result = mismatch(d1.begin(), d1.end(), d2.begin());


and no data matched you would get a pair of iterator holding d1.begin() and d2.begin(),

This is ambiguous as you do not know if ALL data is mismatched or the first elements

or am I being a bit dozy?
Last edited on
Returns the first mismatching pair of elements from two ranges

That to me says: either there are no mismatches, or there is at least one.

Just two cases. Only if the mismatch is found in the last element, then you know that there is only one mismatch. In all other cases of mismatches there could be more.

If you want them all, then you probably have to do something like:
1
2
3
4
5
auto result = mismatch(d1.begin(), d1.end(), d2.begin());
while (result.first != d1.end() ) {
  // use result
  result = mismatch(result.first+1, d1.end(), result.second+1);
}
You are misreading the docs, sorry.
https://en.cppreference.com/w/cpp/algorithm/mismatch#Return_value

Return value 
std::pair with iterators to the first two non-equal elements.

(until C++14)
If no mismatches are found when the comparison reaches last1, the pair holds last1 and the corresponding iterator from the second range. The behavior is undefined if the second range is shorter than the first range.

(since C++14)
If no mismatches are found when the comparison reaches last1 or last2, whichever happens first, the pair holds the end iterator and the corresponding iterator from the other range.

All the verbiage is to say that last1 and last2 might not actually be range1.end() or range2.end(), even though they are to be treated as such in the context of this function’s operation.

So, when the function terminates, it either:

  • succeeds in finding a mismatch
    ((result.first != last1) and (result.second != last2),

  • or fails to find a mismatch
    ((result.first == last1) or (result.second == last2).

Whether or not you need to actually check result.second depends on which overload of the algorithm you use and how carefully you use it.
Registered users can post here. Sign in or register to post.