Boost MultiIndex - objects or pointers (and how to use them?)

I program agent-based simulation and decided that Boost MultiIndex is probably the most efficient container for my agents. I am not a professional programmer, and my background is very spotty. I have two questions:

  • Is it better to contain agents ( Host class) in the container, or is it more efficient for storing the Host * container? Hosts are sometimes deleted from memory (which is my plan, anyway ... you need to read on new and delete ). Private host variables will be updated periodically, which I hope to do with the modify function in MultiIndex. There will be no other host copies in the simulation, i.e. They will not be used in any other containers.
  • If I use pointers to Hosts, how do I configure key extraction correctly? My code below does not compile.
 // 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 ); ... } 

I cannot find exactly the same example in the Boost documentation, and my knowledge of C ++ syntax is still very weak. The code really works when I replace all the pointer links to the class objects themselves.


As far as I can read this, the Boost documentation (see the pivot table below) implies that I should be able to use member functions with pointer elements.

+6
c ++ boost hash
source share
1 answer

If Host contains a lot of data, you can use shared_ptr to avoid copying. You can use MultiIndex with shared_ptr in it:

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

Then you can use it as follows:

 int main() { HostContainer testHosts; Host * newHostPtr; newHostPtr = new Host; testHosts.insert( boost::shared_ptr<Host>(newHostPtr) ); return 0; } 
+7
source share

All Articles