STL icon indicating copy to clipboard operation
STL copied to clipboard

Should `stable_sort` accept bidirectional iterator?

Open TPPPP72 opened this issue 7 months ago • 3 comments

I noticed that MSVC's stable_sort function signature accepts a bidirectional iterator instead of the standard random access iterator, which allows the following code to compile.

#include <algorithm>
#include <iostream>
#include <list>

int main()
{
    std::list<int> test{1, 2, 4, 5, 3};
    std::stable_sort(test.begin(), test.end());
    for (auto i : test)
    {
        std::cout << i << '\n';
    }
}

https://godbolt.org/z/oGr5rPaja However, since both gcc and clang refuse to compile this code, I think this could lead to compiler inconsistencies and misuse of bootstraps. Is this intentional design?

TPPPP72 avatar Apr 09 '26 12:04 TPPPP72

For now I think it's better disable using non-random-access ranges for std::stable_sort and its friends, which is consistent with ranges versions.

In the future, I think we should investigate whether stable sorting algorithms should require random access. It seemingly make sense to make stable_sort support bidirectional ranges.

frederick-vs-ja avatar Apr 09 '26 16:04 frederick-vs-ja

Oops... https://github.com/microsoft/STL/blob/da06be8fa38418772506328177b703b28ca75699/tests/std/include/instantiate_algorithms.hpp#L611-L614

frederick-vs-ja avatar Apr 10 '26 01:04 frederick-vs-ja

Oops... https://github.com/microsoft/STL/blob/da06be8fa38418772506328177b703b28ca75699/tests/std/include/instantiate_algorithms.hpp#L611-L614

Appears to be an intentional design. Therefore, no need for further discussion.

TPPPP72 avatar Apr 10 '26 01:04 TPPPP72