Skip to content

Instantly share code, notes, and snippets.

@stfuchs
Last active April 25, 2018 18:43
Show Gist options
  • Save stfuchs/991cbbec1f06d85e6d1cb0c5c6704760 to your computer and use it in GitHub Desktop.
Save stfuchs/991cbbec1f06d85e6d1cb0c5c6704760 to your computer and use it in GitHub Desktop.
Container to buffer N max elements
#include <iostream>
#include <string>
#include <algorithm>
template<class Key, class T>
class MaxBuffer
{
typedef std::pair<Key, T> value_type;
typedef typename std::vector<value_type>::iterator iterator;
typedef typename std::vector<value_type>::const_iterator const_iterator;
typedef typename std::vector<value_type>::reverse_iterator reverse_iterator;
typedef typename std::vector<value_type>::const_reverse_iterator const_reverse_iterator;
public:
MaxBuffer(const size_t& size) : v_() , size_(size)
{ v_.reserve(size); }
bool update(const Key& k, const T& v)
{
auto cmp = [](const value_type& a, const value_type& b) {return a.first > b.first;};
if (v_.size() < size_)
{
v_.push_back(std::make_pair(k,v));
std::push_heap(v_.begin(), v_.end(), cmp);
return true;
}
if (v_.front().first < k)
{
std::pop_heap(v_.begin(), v_.end(), cmp);
v_.back() = std::make_pair(k,v);
std::push_heap(v_.begin(), v_.end(), cmp);
return true;
}
return false;
}
inline iterator begin() { return v_.begin(); }
inline iterator end() { return v_.end(); }
inline reverse_iterator rbegin() { return v_.rbegin(); }
inline reverse_iterator rend() { return v_.rend(); }
inline const_iterator begin() const { return v_.begin(); }
inline const_iterator end() const{ return v_.end(); }
inline const_reverse_iterator rbegin() const { return v_.rbegin(); }
inline const_reverse_iterator rend() const { return v_.rend(); }
private:
std::vector<value_type> v_;
size_t size_;
};
template <class T>
void print(const T& v)
{
std::cout << "Elements: ";
for (const auto& e : v)
{
std::cout << "(" << e.first << "," << e.second << ") ";
}
std::cout << std::endl;
}
int main()
{
MaxBuffer<float, std::string> b(3);
b.update(-10,"a"); print(b);
b.update(-2,"b"); print(b);
b.update(-3,"c"); print(b);
b.update(6,"e"); print(b);
b.update(-1,"f"); print(b);
b.update(-6,"e"); print(b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment