| 91 | container_.clear(); |
| 92 | } |
| 93 | void push(int32 a) { |
| 94 | auto comparator = [this](int32 a, int32 b) { return compare_fun(a, b); }; |
| 95 | if (container_.size() <= k_) { |
| 96 | container_.push_back(a); |
| 97 | if (container_.size() == k_ + 1) { |
| 98 | std::make_heap(container_.begin(), container_.end(), comparator); |
| 99 | std::pop_heap(container_.begin(), container_.end(), comparator); |
| 100 | } |
| 101 | } else if (comparator(a, container_.front())) { |
| 102 | // Due to how we defined comparator / compare_fun, container_.front() |
| 103 | // contains the index of the smallest of the top-k elements seen so far. |
| 104 | // |
| 105 | // If control reaches this point, we know that the current index a |
| 106 | // corresponds to an element which is bigger than the smallest of the |
| 107 | // top-k elements seen so far. Hence, we have to update the indices of |
| 108 | // the top-k elements, by removing the index of the smallest top-k |
| 109 | // element, adding a, and making sure container_[0:k] is still a heap. |
| 110 | |
| 111 | // Store index a into container_[k]. |
| 112 | container_.back() = a; |
| 113 | |
| 114 | // Swap container_[0] and container_[k], and rearrange elements from |
| 115 | // container_[0,k) such that they are a heap according to comparator. For |
| 116 | // more info, see https://en.cppreference.com/w/cpp/algorithm/pop_heap. |
| 117 | std::pop_heap(container_.begin(), container_.end(), comparator); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | const std::vector<int32>& sorted_result() { |
| 122 | auto comparator = [this](int32 a, int32 b) { return compare_fun(a, b); }; |
no test coverage detected