I have some code which is showing odd behavior when std::is_sorted() is called twice in a row; the result changes! The fist call returns false and the second call returns true. This happens with the following
Apple clang version 15.0.0 (clang-1500.3.9.4)Ubuntu clang version 15.0.7Ubuntu clang version 18.1.3 (1ubuntu1)
while compiling with -O2 -std=c++20. I also tested with c++11 and c++17. The code below uses a sort algorithm to sort a std::array<> then check to see that it is std::is_sorted(). This is actually a minimum reproduction of a test case in another code base. I believe the algorithm is correct. If I print the contents of the array before calling std::is_sorted() the contents are printed in the expected order and both calls to std::is_sorted() return true. I cannot reproduce this on lower optimization levels and GNU g++ performed as expected.
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
template<class T>
void insertion_sort(T begin, T end)
{
T current = begin;
++current;
while(current < end) {
auto key = *current;
auto j = current - 1;
while(j >= begin && *j > key) {
*(j+1) = *j;
--j;
}
*(j+1) = key;
current++;
}
}
int main(int argc, char* argv[])
{
std::array<int, 6> a{5, 2, 4, 6, 1, 3};
insertion_sort(a.begin(), a.end());
std::cout << std::is_sorted(a.begin(), a.end()) << std::endl;
std::cout << std::is_sorted(a.begin(), a.end()) << std::endl;
return 0;
}
beginis UB.--jexhibits undefined behavior whenj == begininsertion_sortwithstd::sortto see that the code is wrong, asstd::sortwould not have exhibited this behavior. Also, what you wrote is not an algorithm, it is code that is supposed to implement the insertion sort algorithm. Algorithms are never wrong, code that attempts to implement the algorithm can be wrong. Also you could test the insertion sort code found here.