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

标签 c++ boost hash

我正在编写一个基于代理的模拟,并认为 Boost 的 MultiIndex 可能是我的代理最有效的容器。我不是专业的程序员,我的背景参差不齐。我有两个问题:

  1. 是让容器本身包含代理(类 Host)更好,还是让容器保存 Host * 更有效?主机有时会从内存中删除(这是我的计划,无论如何......需要阅读 newdelete)。主机的私有(private)变量会偶尔更新,我希望通过 MultiIndex 中的 modify 函数来完成。模拟中不会有其他主机拷贝,即它们不会在任何其他容器中使用。
  2. 如果我使用指向主机的指针,我该如何正确设置 key 提取?我的以下代码无法编译。
// 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 );
   ... 
}

我在 Boost 文档中找不到精确类似的示例,而且我对 C++ 语法的了解还很薄弱。当我用类对象本身替换所有指针引用时,代码似乎确实有效。


据我所知,Boost documentation (请参阅底部的汇总表)暗示我应该能够使用带有指针元素的成员函数。

最佳答案

如果 Host 包含大量数据,您可以使用 shared_ptr 来避免复制。您可以将 MultiIndex 与 shared_ptr 一起使用:

#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;

然后你可以按如下方式使用它:

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

  return 0;
}

关于c++ - Boost MultiIndex - 对象或指针(以及如何使用它们?)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2648176/

相关文章:

c++ - 访问父类的成员 "Invalid use of non-static data member"C++

c++ - 将 numpy 数组与 boost.python : pyublas or boost. numpy 交换?

c++ - 在 boost::property_tree::read_xml 中捕获异常

swift - 我该怎么做才能快速安全地存储密码?

c++ - Direct3D9 游戏 : Spaceship camera

c# - 如何在 Unity 3D 中包含 SWIG 封装的 C++?

c++ - C++ 中的冲突声明

c++ - 使用带有 EMBARCADERO RAD C++ XE5 的 Boost 图形库

Java SHA256 哈希与 vb.net 中的不同

对于未知输入具有良好均匀性的哈希函数