[stl-extras] Provide an adaptor of std::count for ranges.
authorMichael Gottesman <mgottesman@apple.com>
Sun, 4 Dec 2016 10:26:53 +0000 (10:26 +0000)
committerMichael Gottesman <mgottesman@apple.com>
Sun, 4 Dec 2016 10:26:53 +0000 (10:26 +0000)
llvm-svn: 288619

llvm/include/llvm/ADT/STLExtras.h
llvm/unittests/ADT/STLExtrasTest.cpp

index 28e1553..4435b46 100644 (file)
@@ -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 <typename R, typename E>
+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 <typename R, typename UnaryPredicate>
index 44c0044..7688129 100644 (file)
@@ -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<int> 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));
+}
 }