jubatus_core  0.1.2
Jubatus: Online machine learning framework for distributed environment
fixed_size_heap.hpp
Go to the documentation of this file.
1 // Jubatus: Online machine learning framework for distributed environment
2 // Copyright (C) 2012 Preferred Networks and Nippon Telegraph and Telephone Corporation.
3 //
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License version 2.1 as published by the Free Software Foundation.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16 
17 #ifndef JUBATUS_CORE_STORAGE_FIXED_SIZE_HEAP_HPP_
18 #define JUBATUS_CORE_STORAGE_FIXED_SIZE_HEAP_HPP_
19 
20 #include <algorithm>
21 #include <functional>
22 #include <vector>
23 
24 namespace jubatus {
25 namespace core {
26 namespace storage {
27 
28 template <typename T, typename Comp = std::less<T> >
30  public:
31  explicit fixed_size_heap(size_t max)
32  : max_size_(max),
33  comp_(Comp()) {
34  }
35 
36  fixed_size_heap(size_t max, const Comp& comp)
37  : max_size_(max),
38  comp_(comp) {
39  }
40 
41  void push(const T& v) {
42  if (data_.size() < max_size_) {
43  data_.push_back(v);
44  if (data_.size() == max_size_) {
45  std::make_heap(data_.begin(), data_.end(), comp_);
46  }
47  } else {
48  if (max_size_ > 0 && comp_(v, data_.front())) {
49  std::pop_heap(data_.begin(), data_.end(), comp_);
50  data_.back() = v;
51  std::push_heap(data_.begin(), data_.end(), comp_);
52  }
53  }
54  }
55 
56  void get_sorted(std::vector<T>& v) const {
57  std::vector<T> vec(data_);
58  std::sort(vec.begin(), vec.end(), comp_);
59  v.swap(vec);
60  }
61 
62  size_t size() const {
63  return data_.size();
64  }
65 
66  size_t get_max_size() const {
67  return max_size_;
68  }
69 
70  private:
71  std::vector<T> data_;
72  const size_t max_size_;
73  const Comp comp_;
74 };
75 
76 } // namespace storage
77 } // namespace core
78 } // namespace jubatus
79 
80 #endif // JUBATUS_CORE_STORAGE_FIXED_SIZE_HEAP_HPP_
void get_sorted(std::vector< T > &v) const
std::vector< T > v(size)
fixed_size_heap(size_t max, const Comp &comp)