Any feedback regarding this proposal:
https://gcc.gnu.org/pipermail/libstdc++/2021-June/052821.html
On 23/06/21 22:34, François Dumont wrote:
Hi
Following the message to propose an alternative lower_bound and the
reply to use three way comparison I try to implement this.
Before going further I wonder if this is something possible ?
The purpose of the:
if constexpr (three_way_comparable<>)
is to make sure that we use it only if there is a proper <=> operator
defined. Afai understood what is in <compare> we can have the
__synth3way for any type as long as < exist. But I think that if <=>
is implemented in terms of < then it might be too expensive, the
actual lower_bound might already be implemented this way.
My main concerns is of course Standard conformity, could it be ok ?
François
diff --git a/libstdc++-v3/include/bits/stl_algobase.h b/libstdc++-v3/include/bits/stl_algobase.h
index 84a1f9e98f6..7a0c42a4909 100644
--- a/libstdc++-v3/include/bits/stl_algobase.h
+++ b/libstdc++-v3/include/bits/stl_algobase.h
@@ -1472,6 +1472,48 @@ _GLIBCXX_END_NAMESPACE_CONTAINER
return __first;
}
+#if __cpp_lib_three_way_comparison
+ template<typename _ForwardIterator, typename _Tp, typename _Compare>
+ _GLIBCXX20_CONSTEXPR
+ _ForwardIterator
+ __lower_bound_three_way(_ForwardIterator __first, _ForwardIterator __last,
+ const _Tp& __val, _Compare __comp)
+ {
+ auto __len = std::distance(__first, __last);
+
+ while (__len > 0)
+ {
+ auto __half = __len >> 1;
+ if (__half == 0)
+ {
+ if (auto __c = __comp(*__first, __val); __c < 0)
+ return std::next(__first);
+ return __first;
+ }
+
+ _ForwardIterator __prev_mid = __first;
+ std::advance(__prev_mid, __half - 1);
+ _ForwardIterator __middle = std::next(__prev_mid);
+ if (auto __c = __comp(*__middle, __val); __c != 0)
+ {
+ if (__c < 0)
+ {
+ __first = __middle;
+ ++__first;
+ __len = __len - __half - 1;
+ }
+ else
+ __len = __half;
+ }
+ else if (__c = __comp(*__prev_mid, __val); __c != 0)
+ return __middle;
+ else // __c == 0.
+ __len = __half - 1;
+ }
+ return __first;
+ }
+#endif
+
/**
* @brief Finds the first position in which @a val could be inserted
* without changing the ordering.
@@ -1495,6 +1537,13 @@ _GLIBCXX_END_NAMESPACE_CONTAINER
typename iterator_traits<_ForwardIterator>::value_type, _Tp>)
__glibcxx_requires_partitioned_lower(__first, __last, __val);
+#if __cpp_lib_three_way_comparison
+ if constexpr (three_way_comparable_with<
+ typename iterator_traits<_ForwardIterator>::reference,
+ const _Tp&>)
+ return std::__lower_bound_three_way(__first, __last, __val,
+ compare_three_way{});
+#endif
return std::__lower_bound(__first, __last, __val,
__gnu_cxx::__ops::__iter_less_val());
}