开发者

Given the following typedefs, what syntax would be used to insert an object?

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 th开发者_如何学Ce 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?


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.


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


ObjectPtr obj;
ObjectList olist;

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


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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜