3

I've got typedef'd two maps

typedef std::map<std::string, std::map<std::string, migrationObj> > table;
typedef std::map<std::string, migrationObj> obj;

int main (int argc, char ** argv) {
   table t;
   t["test"].insert(obj::value_type("testID", 1));
   return 0;
}

how would I be able to add a custom method to type table (lets call it createItem), so that I can do

t["test"].createItem("testID", 1);

I know this looks a bit overhead to do this, but I've simplified the problem. The reason for me doing this is that I still need to do something in the createItem to keep track of the insertion order of the map while maintaining the key lookup feature of a map.

toxicate20
  • 5,270
  • 3
  • 26
  • 38
  • 5
    Off topic, but I wish I had a shirt that said `I got typedef'd` .. Thanks for the idea! – Steven Maitlall May 29 '13 at 19:24
  • possible duplicate of [Adding custom methods to std::vector or typdef](http://stackoverflow.com/questions/16812606/adding-custom-methods-to-stdvector-or-typdef) – Arne Mertz May 29 '13 at 19:40

2 Answers2

4

I suppose you have ruled out a wrapper object, but it is still a valid solution.

class obj {
    typedef std::map<std::string, migrationObj> maptype;
    maptype m_;
public:
    maptype * operator -> () { return &m_; }
    const maptype * operator -> () const { return &m_; }
    maptype & map () { return m_; }
    const maptype & map () const { return m_; }
    void createItem (std::string key, int value) {
        // ... your custom code ...
        m_.insert(maptype::value_type(key, value));
    }
    //...
};
jxh
  • 69,070
  • 8
  • 110
  • 193
0

boost::multi_index might be the right answer here.

A std::map that keep track of the order of insertion?

http://www.boost.org/libs/multi_index

Community
  • 1
  • 1
Steven Maitlall
  • 777
  • 3
  • 5
  • I know this one, and what I would want to implement is http://stackoverflow.com/a/1098236/1479913 but there is going to be a lot of creation of objects going on (large data analysis) and therefore I need to do this every time. Thats why I want to add a custom function to the typedef'd map. – toxicate20 May 29 '13 at 19:35
  • Looking more closely at the documentation, the insertion performance could be better for boost::multi_index than std::map. `From the point of view of computational complexity (i.e. big-O characterization), multi_index_container and its corresponding manual simulations are equivalent: inserting an element into a multi_index_container reduces to a simple combination of elementary insertion operations on each of the indices, and similarly for deletion.` – Steven Maitlall May 29 '13 at 19:52