Skip to content

Commit 6b4b8dc

Browse files
aws-taylorkuhar
andauthored
[ADT] Relax iterator constraints on all_equal (#106400)
The previous `all_equal` implementation contained `Begin + 1`, which implicitly requires `Begin` to model the [random_access_iterator](https://en.cppreference.com/w/cpp/iterator/random_access_iterator) concept due to the usage of the `+` operator. By swapping this out with `std::next`, this method can be used with weaker iterator concepts, such as [forward_iterator](https://en.cppreference.com/w/cpp/iterator/forward_iterator). --------- Co-authored-by: Jakub Kuderski <[email protected]>
1 parent aa7497a commit 6b4b8dc

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

llvm/include/llvm/ADT/STLExtras.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -2062,7 +2062,7 @@ bool equal(L &&LRange, R &&RRange, BinaryPredicate P) {
20622062
template <typename R> bool all_equal(R &&Range) {
20632063
auto Begin = adl_begin(Range);
20642064
auto End = adl_end(Range);
2065-
return Begin == End || std::equal(Begin + 1, End, Begin);
2065+
return Begin == End || std::equal(std::next(Begin), End, Begin);
20662066
}
20672067

20682068
/// Returns true if all Values in the initializer lists are equal or the list

llvm/unittests/ADT/STLExtrasTest.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include <climits>
1616
#include <cstddef>
1717
#include <initializer_list>
18+
#include <iterator>
1819
#include <list>
1920
#include <tuple>
2021
#include <type_traits>
@@ -831,6 +832,26 @@ TEST(STLExtrasTest, AllEqual) {
831832
EXPECT_FALSE(all_equal(V));
832833
}
833834

835+
// Test to verify that all_equal works with a container that does not
836+
// model the random access iterator concept.
837+
TEST(STLExtrasTest, AllEqualNonRandomAccess) {
838+
std::list<int> V;
839+
static_assert(!std::is_convertible_v<
840+
std::iterator_traits<decltype(V)::iterator>::iterator_category,
841+
std::random_access_iterator_tag>);
842+
EXPECT_TRUE(all_equal(V));
843+
844+
V.push_back(1);
845+
EXPECT_TRUE(all_equal(V));
846+
847+
V.push_back(1);
848+
V.push_back(1);
849+
EXPECT_TRUE(all_equal(V));
850+
851+
V.push_back(2);
852+
EXPECT_FALSE(all_equal(V));
853+
}
854+
834855
TEST(STLExtrasTest, AllEqualInitializerList) {
835856
EXPECT_TRUE(all_equal({1}));
836857
EXPECT_TRUE(all_equal({1, 1}));

0 commit comments

Comments
 (0)