如何在结构内的向量中推回对象

时间:2019-06-12 02:31:54

标签: c++ pointers vector struct

我正在使用二进制树对程序进行编码,我需要添加一个节点作为子节点,因此我使用了结构。因此,我试图通过寻找父亲的地址来添加孩子,但我不断收到一个错误消息,即没有已知的转换

struct PERSON {
  string name;
  vector<PERSON> childs;
  PERSON *father;
};

typedef PERSON *Tree;

PERSON * searchPerson(Tree p, string name){
for(int i=0; i <= p->childs.size(); i++){
    if(p->childs[i].name == name){
        return p;
        break;
    }
}
  return nullptr;
}

void add(Tree p, string nameChild, string nameFa){
  PERSON *newPerson = new PERSON;
  PERSON *father = searchPerson(p, nameFa); // its actually a function that return the adresse of the person

  newPerson->name = nameChild;
  newPerson->father = father;

  father->childs.push_back(newPerson);
}

int main(){
  Tree r = nullptr;

  PERSON *p = searchPerson(r, "Test");

  return 0;
}

1 个答案:

答案 0 :(得分:1)

新功能是什么? new是保留的C ++关键字。您不能将其传递给函数。

 father->childs.push_back(new);

相反,您想这样称呼:

 father->childs.push_back(*newPerson);

此外,避免使用普通的指针来管理内存分配。使用smart pointers可以在销毁后重新分配内存。