Boost MultiIndex - 对象或指针(以及如何使用它们?)?

Sar*_*rah 7 c++ hash boost

我正在编写一个基于代理的模拟,并且已经确定Boost的MultiIndex可能是我的代理最有效的容器.我不是一个专业的程序员,我的背景很不稳定.我有两个问题:

  1. 容器Host本身是否包含代理(类)是否更好,或容器容纳更高效Host *?主机有时会从内存中删除(这是我的计划,无论如何......需要阅读new并且delete).主机的私有变量会偶尔更新,我希望通过modifyMultiIndex中的函数来完成.模拟中不会有其他主机副本,即它们不会在任何其他容器中使用.
  2. 如果我使用指向主机的指针,如何正确设置密钥提取?我的代码不能编译.
// main.cpp - ATTEMPTED POINTER VERSION
...
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/tokenizer.hpp>

typedef multi_index_container<
  Host *,
  indexed_by< 
    // hash by Host::id
    hashed_unique< BOOST_MULTI_INDEX_MEM_FUN(Host,int,Host::getID) > // arg errors here
    > // end indexed_by
  > HostContainer;

...
int main() {

   ...
   HostContainer testHosts;
   Host * newHostPtr;
   newHostPtr = new Host( t, DOB, idCtr, 0, currentEvents );
   testHosts.insert( newHostPtr );
   ... 
}
Run Code Online (Sandbox Code Playgroud)

我在Boost文档中找不到一个精确类似的例子,而且我对C++语法的了解仍然非常薄弱.当我用类对象本身替换所有指针引用时,代码似乎工作.


最好我可以阅读它,Boost 文档(见底部的摘要表)暗示我应该能够使用带有指针元素的成员函数.

Kir*_*sky 10

如果Host包含大量数据,可以使用shared_ptr以避免复制.您可以shared_ptr在其中使用MultiIndex :

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/shared_ptr.hpp>

using namespace boost::multi_index;

struct Host
{
   int get_id() const { return id; }
 private:
   int id;
   // more members here
};

typedef multi_index_container<
  boost::shared_ptr<Host>,    // use pointer instead of real Host
  indexed_by< 
    // hash using function Host::get_id
    hashed_unique< const_mem_fun<Host, int, &Host::get_id> >
    > // end indexed_by
  > HostContainer;
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它如下:

int main()
{
   HostContainer testHosts;
   Host * newHostPtr;
   newHostPtr = new Host;
   testHosts.insert( boost::shared_ptr<Host>(newHostPtr) );

  return 0;
}
Run Code Online (Sandbox Code Playgroud)