C ++如何将地图与循环缓冲区混合? [英] C++ how to mix a map with a circular buffer?

查看:92
本文介绍了C ++如何将地图与循环缓冲区混合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能像boost循环缓冲区那样工作的映射.这意味着它将具有有限的大小,并且当它达到其有限的大小时,它将开始覆盖第一个插入的元素.我也希望能够通过[name]通过此类缓冲区和find or create进行搜索.是否有可能创建这样的东西以及如何做?

I wonder is it possible to have a map that would work like boost circular buffer. Meaning it would have limited size and when it would get to its limited size it will start overwriting first inserted elements. Also I want to be capable to search thru such buffer and find or create with [name]. Is It possible to create such thing and how to do it?

推荐答案

好吧,我认为Boost中没有现成的结构(尽管可能存在于其他地方),所以应该创建它.但是,我不建议使用operator[](),至少在std::map中已实现,因为这可能会导致难以跟踪添加到地图中的元素(例如,将operator[]()与值一起使用会添加该空值到地图),然后进行更明确的获取和放置操作,以添加和检索地图元素.

Well, I don't think that structure is present out of the box in boost (may exist elsewhere, though), so you should create it. I wouldn't recommend using operator[](), though, at least as it is implemented in std::map, because this may make difficult to track elements added to the map (for exapmle, using operator[]() with a value adds that empty value to the map), and go for a more explicit get and put operations for adding and retrieving elements of the map.

对于最简单的实现,我将使用实际的map作为存储,并使用deque作为添加的元素的存储(未测试):

As for the easiest implementation, I would go for using an actual map as the storage, and a deque for the storage of the elements added (not tested):

template <typename K, typename V>
struct BoundedSpaceMap
{
    typedef std::map<K,V> map_t;
    typedef std::deque<K> deque_t;

    // ...
    typedef value_type map_t::value_type;
    // Reuse map's iterators
    typedef iterator map_t::iterator;

    // ...
    iterator begin() { return map_.begin(); }

    // put
    void put ( K k, V v)
    { map_.insert(std::make_pair(k,v));
      deque_.push_back(k);
      _ensure();  // ensure the size of the map, and remove the last element
    }

     // ...

private:
     map_t map_;
     deque_t deque_;

     void _ensure() { 
       if (deque_size() > LIMIT) { 
         map_.erase(deque_.front()); deque_.pop_front();
       }
     }
};

这篇关于C ++如何将地图与循环缓冲区混合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆