From 6a2af3eb1dea251bd98d4d995153021a74c9cecc Mon Sep 17 00:00:00 2001 From: Michael Gottesman Date: Sun, 4 Dec 2016 10:26:53 +0000 Subject: [PATCH] [stl-extras] Provide an adaptor of std::count for ranges. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@288619 91177308-0d34-0410-b5e6-96231b3b80d8 --- include/llvm/ADT/STLExtras.h | 8 ++++++++ unittests/ADT/STLExtrasTest.cpp | 17 +++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/include/llvm/ADT/STLExtras.h b/include/llvm/ADT/STLExtras.h index 28e1553606c..4435b46f462 100644 --- a/include/llvm/ADT/STLExtras.h +++ b/include/llvm/ADT/STLExtras.h @@ -639,6 +639,14 @@ bool is_contained(R &&Range, const E &Element) { std::end(Range); } +/// Wrapper function around std::count to count the number of times an element +/// \p Element occurs in the given range \p Range. +template +auto count(R &&Range, const E &Element) -> typename std::iterator_traits< + decltype(std::begin(Range))>::difference_type { + return std::count(std::begin(Range), std::end(Range), Element); +} + /// Wrapper function around std::count_if to count the number of times an /// element satisfying a given predicate occurs in a range. template diff --git a/unittests/ADT/STLExtrasTest.cpp b/unittests/ADT/STLExtrasTest.cpp index 44c0044c25d..76881296db6 100644 --- a/unittests/ADT/STLExtrasTest.cpp +++ b/unittests/ADT/STLExtrasTest.cpp @@ -236,4 +236,21 @@ TEST(STLExtrasTest, ApplyTupleVariadic) { EXPECT_EQ("Tes", std::get<1>(Values)); EXPECT_EQ('Y', std::get<2>(Values)); } + +TEST(STLExtrasTest, CountAdaptor) { + std::vector v; + + v.push_back(1); + v.push_back(2); + v.push_back(1); + v.push_back(4); + v.push_back(3); + v.push_back(2); + v.push_back(1); + + EXPECT_EQ(3, count(v, 1)); + EXPECT_EQ(2, count(v, 2)); + EXPECT_EQ(1, count(v, 3)); + EXPECT_EQ(1, count(v, 4)); +} }