C++ boost multi_索引提取的密钥是否缓存?

C++ boost multi_索引提取的密钥是否缓存?,c++,boost,multi-index,boost-multi-index,C++,Boost,Multi Index,Boost Multi Index,我正在使用boost::multi_索引和一种数据类型,我希望根据其大小对其进行索引。但是,此数据类型的size()成员函数的执行成本很高。multi_索引是否缓存从其密钥提取器获取的值 例如,如果我创建了一个带有一个成员函数键(元素.sie())的有序索引的多个索引容器,并插入一个元素,该元素的大小放在容器的中间,容器将重新调用siz()。在找到正确的插入点之前,在遍历其内部数据结构的同时访问所有元素上的成员函数?成员函数索引器的文档称,它们调用引用的成员函数: 但当有疑问时,简介: #inc

我正在使用boost::multi_索引和一种数据类型,我希望根据其大小对其进行索引。但是,此数据类型的size()成员函数的执行成本很高。multi_索引是否缓存从其密钥提取器获取的值


例如,如果我创建了一个带有一个成员函数键(元素.sie())的有序索引的多个索引容器,并插入一个元素,该元素的大小放在容器的中间,容器将重新调用siz()。在找到正确的插入点之前,在遍历其内部数据结构的同时访问所有元素上的成员函数?

成员函数索引器的文档称,它们调用引用的成员函数:

但当有疑问时,简介:

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/indexed_by.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

namespace bmi = boost::multi_index;

int g_calls = 0;
struct A
{
  explicit A(int sz) : m_size(sz) { }
  int size() const { ++g_calls; return m_size; }
private:
  int m_size;
};

typedef boost::multi_index_container<
  A*,
  bmi::indexed_by<
    bmi::ordered_non_unique<
      BOOST_MULTI_INDEX_CONST_MEM_FUN(A,int,A::size)
    >
  >
> container_t;

int main()
{
  container_t cont;
  int n = 100;
  vector<int> o(2*n+1);
  for( int i = 0; i != 2*n+1; ++i )
    o[i] = i;
  random_shuffle(o.begin(), o.end());

  for( int i = 0; i != n; ++i )
    cont.insert(new A(o[i]));
  cout << "Calls to A::size(): "<< g_calls << endl;
  for( int i = n+1; i <= 2*n; ++i )
    cont.insert(new A(o[i]));
  cout << "Calls to A::size(): "<< g_calls << endl;
  cont.insert(new A(o[n]));
  cout << "Calls to A::size(): "<< g_calls << endl;
  for( int i = 0; i != o.size(); ++i )
    cont.find(o[i]);
  cout << "Calls after calling find " << o.size() << " times: "<< g_calls << endl;
  return 0;
}

因此,答案似乎是否定的,它不会缓存值。

太棒了,谢谢。太糟糕了。我想我必须包装我的类型。你可能想自己缓存它。你需要在你的对象里面有一个
大小\u t
,也许还有一个“脏”位,这样你就知道你是否缓存了它,缓存是否是最新的。
Calls to A::size(): 629
Calls to A::size(): 1465
Calls to A::size(): 1474
Calls after calling find 201 times: 3262