有什么办法来限制STL Map的大小吗? [英] Is there any way to limit the size of an STL Map?

查看:659
本文介绍了有什么办法来限制STL Map的大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中实现某种类型的查找表,作为缓存。这是为了模拟我模拟的一块硬件。

I want to implement some sort of lookup table in C++ that will act as a cache. It is meant to emulate a piece of hardware I'm simulating.

键是非整数,所以我猜哈希是顺序。我没有意图发明轮,所以我打算使用 std :: map 这(尽管建议替代品是欢迎的)。

The keys are non-integer, so I'm guessing a hash is in order. I have no intention of inventing the wheel so I intend to use std::map for this (though suggestions for alternatives are welcome).

问题是,有没有办法限制散列的大小来模拟我的硬件是有限大小的事实?我希望哈希的 insert 方法返回一个错误消息或者在达到限制时抛出异常。

The question is, is there any way to limit the size of the hash to emulate the fact that my hardware is of finite size? I'd expect the hash's insert method to return an error message or throw an exception if the limit is reached.

如果没有

推荐答案

解决方案,你可以做的是封装实际的数据结构到一个类,检查每个插入的大小(大小查找应该在所有STL实现中的恒定时间实现),如果你试图添加一个太多的元素。

The simplest solution that you can do is encapsulate the actual data structure into a class that checks the size in each insertion (size lookups should be implemented in constant time in all STL implementations) and fails if you are trying to add one too many elements.

class cache {
public:
   static const int max_size = 100;
   typedef std::map<key_t, value_t> cache_map_t;
   void add( key_t key, value_t value ) {
      cache_map_t::const_iterator it = m_table.find( key );
      if ( it != m_table.end() && m_table.size() == max_size ) { 
         // handle error, throw exception...
      } else {
         m_table.insert( it, std::make_pair(key,value) );
      }
   }
private:
   cache_map_t m_table;
};
// Don't forget, in just one translation unit:
const int cache::max_size;

这篇关于有什么办法来限制STL Map的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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