tags:

views:

60

answers:

4

I inherited some C++ code and am trying to extend it and need to insert some objects into the following data structures in order to call a method, as the ObjectList is part of the parameter list that is passed to the method.

typedef std::vector <std::pair <std::string, ObjectPtr> >       ObjectListBase;
typedef boost::shared_ptr <ObjectListBase>              ObjectList;

What would be the appropriate syntax to add on object to this vector of maps?

A: 

The data type being inserted is an std::pair. The syntax would be:

ObjectPtr oPtr;
ObjecList.push_back( std::pair<std::string, ObjectPtr>("ABC", oPtr) );
skimobear
+2  A: 

objectList->push_back(std::make_pair(myStringKey, anObjectPtr))

This interface smells of the antipattern primitive obsession. If you change how your objects are stored (decide to use a class instead of std::pair, for example), all your client code is affected.

Alex Emelianov
That did the trick, thank you kindly. Interesting reference to the primitive obsession anti-pattern. I'm tempted to refactor, but I just need this one method call to make this patch work and I'm good.
Mike Bacus
A: 
ObjectPtr obj;
ObjectList olist;

olist->push_back(std::make_pair("some_string", obj));
Donotalo
A: 

You are probably looking for something like below (I provided some ObjectPtr to have a working exemple, as OP did not). I would not comment on the exemple, but I also smell some anti-pattern like primitive-obsession.

#include <string>
#include <vector>
#include <iostream>
#include <boost/shared_ptr.hpp>

typedef struct {
    int a;
    int b;
} Object;

typedef Object * ObjectPtr;

typedef std::vector <std::pair <std::string, ObjectPtr > > ObjectListBase;
typedef boost::shared_ptr<ObjectListBase> ObjectList;


void f(ObjectList ol){
    std::cout << 
        "(" << (*ol)[0].first 
            << ", {" << (*ol)[0].second->a << ',' << (*ol)[0].second->b << "})"
             << '\n';
}

int main(){

    Object o = {1, 2};

    std::pair<std::string, ObjectPtr> p = std::make_pair(std::string("toto"), &o);
    ObjectListBase & olb = *(new ObjectListBase());
    olb.push_back(std::make_pair(std::string("toto"), &o));

    std::cout << 
        "(" << olb[0].first 
            << ", {" << olb[0].second->a << ',' << olb[0].second->b << "})"
             << '\n';

    f(ObjectList(&olb));
}
kriss