如何将值分配给类型为 std::map<std::string,shared_ptr<A>>

how do i assign value to member variable of type std::map<std::string,shared_ptr<A>>

本文关键字:std lt gt string shared ptr map 分配 类型      更新时间:2023-10-16

我第一次尝试boost lib,不知道如何分配字符串映射和共享指针。这是我的代码,我正在尝试赋值,但无法执行。

#include <boostshared_ptr.hpp>
#include <boostassign.hpp>
#include <boostmap.hpp>
struct X
{
   public:
      int p;
      double q;
      X();
     ~X();
};
struct Y
{
    float m;
    double n;
     Y();
    ~Y();
};
struct Z
{
public:
   std::map<std::string,boost::shared_ptr<X>> Xtype;
   std::map<std::string,boost::shared_ptr<Y>> Ytype; 
   int i;
   string name; 
   Z();
  ~Z();
};
struct X *x1;
struct Y *y1;
void setx()
{
  x1->p=10;
  x1->q=20.20;
}

void sety()
{
   y1->m=10;
   y1->n=20.20;
};
void initialize(Z *z1)
{
    z1->i=30;
    // how to i add x1 and y1 to Xtype and Ytype respectively of z1 struct
}

我的问题是:如何将x1和y1值分配给z1类型的Xtype和Ytype。真的不知道该做什么以及如何开始。如果我能够分配,那么我可以继续对它进行序列化。

只需使用[]运算符:

std::map<std::string, some_type> my_map;
some_type object=get_object();        // an object that you want to insert into the map
std::string key=get_key();            // the key you want to associated with object
assert(my_map.empty());               // no keys in map yet! (only for demonstration)
my_map[key] = object;

如果映射已经包含所提供的键,则替换该键的对象否则,将生成映射中的新条目,并使用对象进行初始化。在这里阅读更多关于std::map的信息(如果你还不知道shared_ptr<>,并且不能百分之百确定它是否需要,请避免使用它)。