https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97828
--- Comment #8 from CVS Commits <cvs-commit at gcc dot gnu.org> --- The master branch has been updated by Patrick Palka <ppa...@gcc.gnu.org>: https://gcc.gnu.org/g:8661f4faa875f361cd22a197774c1fa04cd0580b commit r11-5096-g8661f4faa875f361cd22a197774c1fa04cd0580b Author: Patrick Palka <ppa...@redhat.com> Date: Tue Nov 17 10:28:20 2020 -0500 libstdc++: Fix ranges::search_n for random access iterators [PR97828] My ranges transcription of the std::search_n implementation for random access iterators missed a crucial part of the algorithm which the existing tests didn't exercise. When __remainder is less than __count at the start of an iteration of the outer while loop, it means we're continuing a partial match of __count - __remainder elements from the previous iteration. If at the end of the iteration we don't complete this partial match, we need to reset __remainder so that it's only offset by the size of the most recent partial match before starting the next iteration. This patch fixes this appropriately, mirroring how it's done in the corresponding std::search_n implementation. libstdc++-v3/ChangeLog: PR libstdc++/97828 * include/bits/ranges_algo.h (__search_n_fn::operator()): Check random_access_iterator before using the backtracking implementation. When the backwards scan fails prematurely, reset __remainder appropriately. * testsuite/25_algorithms/search_n/97828.cc: New test.