File indexing completed on 2024-04-06 12:01:18
0001 #ifndef CommonTools_Utils_Selection_h
0002 #define CommonTools_Utils_Selection_h
0003 #include <vector>
0004
0005 template <typename C, typename Selector, typename StoreContainer = std::vector<const typename C::value_type*> >
0006 class Selection {
0007 public:
0008 typedef typename C::value_type value_type;
0009 typedef typename C::size_type size_type;
0010 typedef value_type& reference;
0011 typedef const value_type& const_reference;
0012 Selection(const C& c, const Selector& sel) : select_(sel) {
0013 for (typename C::const_iterator i = c.begin(); i != c.end(); ++i) {
0014 if (select_(*i))
0015 selected_.push_back(&*i);
0016 }
0017 }
0018 class const_iterator {
0019 public:
0020 typedef typename Selection<C, Selector, StoreContainer>::value_type value_type;
0021 typedef value_type* pointer;
0022 typedef value_type& reference;
0023 typedef std::ptrdiff_t difference_type;
0024 typedef typename StoreContainer::const_iterator::iterator_category iterator_category;
0025 const_iterator(const typename StoreContainer::const_iterator& it) : i(it) {}
0026 const_iterator(const const_iterator& it) : i(it.i) {}
0027 const_iterator() {}
0028 const_iterator& operator=(const const_iterator& it) {
0029 i = it.i;
0030 return *this;
0031 }
0032 const_iterator& operator++() {
0033 ++i;
0034 return *this;
0035 }
0036 const_iterator operator++(int) {
0037 const_iterator ci = *this;
0038 ++i;
0039 return ci;
0040 }
0041 const_iterator& operator--() {
0042 --i;
0043 return *this;
0044 }
0045 const_iterator operator--(int) {
0046 const_iterator ci = *this;
0047 --i;
0048 return ci;
0049 }
0050 difference_type operator-(const const_iterator& o) const { return i - o.i; }
0051 const_iterator operator+(difference_type n) const { return const_iterator(i + n); }
0052 const_iterator operator-(difference_type n) const { return const_iterator(i - n); }
0053 bool operator<(const const_iterator& o) const { return i < o.i; }
0054 bool operator==(const const_iterator& ci) const { return i == ci.i; }
0055 bool operator!=(const const_iterator& ci) const { return i != ci.i; }
0056 const value_type& operator*() const { return **i; }
0057 const value_type* operator->() const { return &(operator*()); }
0058 const_iterator& operator+=(difference_type d) {
0059 i += d;
0060 return *this;
0061 }
0062 const_iterator& operator-=(difference_type d) {
0063 i -= d;
0064 return *this;
0065 }
0066
0067 private:
0068 typename StoreContainer::const_iterator i;
0069 };
0070 const_iterator begin() const { return const_iterator(selected_.begin()); }
0071 const_iterator end() const { return const_iterator(selected_.end()); }
0072 size_type size() const { return selected_.size(); }
0073 bool empty() const { return selected_.empty(); }
0074 const_reference operator[](size_type i) { return *selected_[i]; }
0075
0076 private:
0077 Selector select_;
0078 StoreContainer selected_;
0079 };
0080
0081 #endif