我正在编写一个基于代理的模拟,并认为 Boost 的 MultiIndex 可能是我的代理最有效的容器。我不是专业的程序员,我的背景参差不齐。我有两个问题:
- 是让容器本身包含代理(类
Host
)更好,还是让容器保存Host *
更有效?主机有时会从内存中删除(这是我的计划,无论如何......需要阅读new
和delete
)。主机的私有(private)变量会偶尔更新,我希望通过 MultiIndex 中的modify
函数来完成。模拟中不会有其他主机拷贝,即它们不会在任何其他容器中使用。 - 如果我使用指向主机的指针,我该如何正确设置 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/