datasketches-cpp
conditional_back_inserter.hpp
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #ifndef CONDITIONAL_BACK_INSERTER_HPP_
21 #define CONDITIONAL_BACK_INSERTER_HPP_
22 
23 #include <iterator>
24 #include <functional>
25 
26 namespace datasketches {
27 
28 template <typename Container, typename Predicate>
29 class conditional_back_insert_iterator: public std::back_insert_iterator<Container> {
30 public:
31  template<typename P>
32  conditional_back_insert_iterator(Container& c, P&& p): std::back_insert_iterator<Container>(c), p(std::forward<P>(p)) {}
33 
34  // MSVC seems to insist on having copy constructor and assignment
35  conditional_back_insert_iterator(const conditional_back_insert_iterator& other):
36  std::back_insert_iterator<Container>(other), p(other.p) {}
37  conditional_back_insert_iterator& operator=(const conditional_back_insert_iterator& other) {
38  std::back_insert_iterator<Container>::operator=(other);
39  p = other.p;
40  return *this;
41  }
42 
43  conditional_back_insert_iterator& operator=(const typename Container::value_type& value) {
44  if (p(value)) std::back_insert_iterator<Container>::operator=(value);
45  return *this;
46  }
47 
48  conditional_back_insert_iterator& operator=(typename Container::value_type&& value) {
49  if (p(value)) std::back_insert_iterator<Container>::operator=(std::move(value));
50  return *this;
51  }
52 
53  conditional_back_insert_iterator& operator*() { return *this; }
54  conditional_back_insert_iterator& operator++() { return *this; }
55  conditional_back_insert_iterator& operator++(int) { return *this; }
56 
57 private:
58  Predicate p;
59 };
60 
61 template<typename Container, typename Predicate>
62 conditional_back_insert_iterator<Container, Predicate> conditional_back_inserter(Container& c, Predicate&& p) {
63  return conditional_back_insert_iterator<Container, Predicate>(c, std::forward<Predicate>(p));
64 }
65 
66 } /* namespace datasketches */
67 
68 #endif
DataSketches namespace.
Definition: binomial_bounds.hpp:38