C++ 将多索引提升为 LRU 缓存的索引排序问题

C++ Index ordering issue with Boost MultiIndex as an LRU cache

本文关键字:索引 缓存 排序 问题 LRU C++      更新时间:2023-10-16

我在这个例子中使用Boost.MultiIndex进行了以下LRU实现。

问题是当我更改index_by部分的顺序(并相应地更新枚举index_idx)时,我在包含以下内容的行上出现错误:

cache_.insert(ci);

具有以下诊断

错误

1 错误 C2661: '提升::multi_index::d尾::sequenced_index::插入" :没有重载函数占用 1 个参数 c:\code\code.cpp 79

代码如下:

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/tag.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
using namespace boost::multi_index;
template <typename Key, typename T>
class lru_cache
{
private:
   struct item_t
   {
      Key key;
      T   t;
   };
   typedef boost::multi_index_container
   <
      item_t,
      boost::multi_index::indexed_by
      <
         hashed_unique<boost::multi_index::member<item_t,Key,&item_t::key> >,
         sequenced<>
      >
   > cache_t;
   enum index_idx
   {
      e_map = 0,
      e_seq = 1,
   };
   cache_t cache_;
   size_t max_cache_size_;
public:
   typedef typename std::pair<Key,T> item_pair_t;
   lru_cache(size_t max_cache_size = 1)
   : max_cache_size_(max_cache_size)
   {}
   bool find(const Key& key, T& t)
   {
      typename cache_t::nth_index<e_map>::type& hash_index = cache_.get<e_map>();
      auto itr = hash_index.find(key);
      if (itr != hash_index.end())
      {
         return false;
      }
      t = itr->t;
      typename cache_t::nth_index<e_seq>::type& sequenced_index = cache_.get<e_seq>();
      auto itr2 = cache_.project<e_seq>(itr);
      sequenced_index.relocate(itr2,sequenced_index.end());
      return true;
   }
   void insert(const Key& key, const T& t)
   {
      if (cache_.size() >= max_cache_size_)
      {
         typename cache_t::nth_index<e_seq>::type& sequenced_index = cache_.get<e_seq>();
         sequenced_index.erase(sequenced_index.begin());
      }
      typename cache_t::nth_index<e_map>::type& hash_index = cache_.get<e_map>();
      auto itr = hash_index.find(key);
      item_t ci = {key,t};
      if (itr == hash_index.end())
         cache_.insert(ci);  // <--- Error here....
      else
         hash_index.replace(itr,ci);
   }
};
int main()
{
   typedef lru_cache<int,int> lru_cache_t;
   lru_cache_t lc(2);
   lc.insert(1,1);
   int v;
   lc.find(1,v);
   return 0;
}

修改后的索引排序:

   typedef boost::multi_index_container
   <
      item_t,
      boost::multi_index::indexed_by
      <
         sequenced<>,
         hashed_unique<boost::multi_index::member<item_t,Key,&item_t::key> >
      >
   > cache_t;
   enum index_idx
   {
      e_map = 1,
      e_seq = 0,
   };

这是因为这个成员函数没有这样的重载!请使用多索引引用。你可能的意思是cache_.insert(cache_.end(), ci);