c++ - vector<unique_ptr<myclass>> 元素之间的指针

标签 c++ c++11 binary-tree stdvector unique-ptr

我有这门课:

#include <iostream>
#include <string>
#include <vector>
#include <memory>

using namespace std;

class person
{
public:
    person(string name, string surname):_name(name), _surname(surname){}
    virtual ~person(){}
    void print()
    { cout  << _name << ' ' << _surname << endl
        << "mother: " << _mother->get_name() << ' ' << _mother->get_surname() << endl
        << "father: " << _father->get_name() << ' ' << _father->get_surname() << endl; 
    }
    string get_name(){return _name;}
    string get_surname(){return _surname;}

    void set_parents(person &mother, person &father)
    {
        _mother = unique_ptr<person>(&mother);
        _father = unique_ptr<person>(&father);
    }
private:
    string _name, _surname;
    unique_ptr<person> _mother, _father;
};

然后是主要功能:

int main()
{
    vector<unique_ptr<person> > people;
    vector<unique_ptr<person> >::iterator iter;

    people.push_back(unique_ptr<person>(new person("Marisa", "Miller")));
    people.push_back(unique_ptr<person>(new person("Andrew", "Clark")));
    people.push_back(unique_ptr<person>(new person("Thomas", "Clark")));
    people.push_back(unique_ptr<person>(new person("Elisa",  "Clark")));
    people.push_back(unique_ptr<person>(new person("Edward",  "Drake")));
    people.push_back(unique_ptr<person>(new person("Jhon",  "Drake")));

    // here is the problem:
    people.at(2).set_parents(???)

    for(iter = people.begin(); iter != people.end(); ++iter)
    {
        (*iter)->print();
    }

    return 0;
}

通过指针,我将定义以下家谱:

[Marisa Miller]     [Andrew Clark]
        |                   |
        +---------+---------+
                  |
                  +--------------[Thomas Clark]
                  |
                  +--------------[Elisa Clark]      [Edward Drake]
                                       |                   |
                                       +---------+---------+
                                                 |
                                           [Jhon Drake]

问题是: 如何将指针(_mother_father,通过 get_parents(...) 函数)设置为 vector 中包含的前一个元素? get_parents() 函数也可以定义为:

void get_parents(person* mother, person* father)

void get_parents(unique_ptr<person> mother, unique_ptr<person> father)

谢谢你的建议

最佳答案

有一个唯一的指针,因此该指针在任何时候最多只在一个地方。您有超过 1 个引用(在 vector 中,如果是父亲或母亲,则可能在人中)。

你可能想看看使用共享指针和弱指针: http://en.cppreference.com/w/cpp/memory/shared_ptr http://en.cppreference.com/w/cpp/memory/weak_ptr

关于c++ - vector<unique_ptr<myclass>> 元素之间的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37345791/

相关文章:

c++ - 获取我可以分配给取消引用的迭代器的类型

c++ - 支持 c++11 的 Makefile

c - 为什么交换二叉树节点时 GDB 观察点会停在不相关的行上?

c++ - 结构 vector ,我不知道该怎么做

c++ - 填充动态数组 C++

c++ - const 转换 std 容器

无法识别类模板的 C++ 成员函数

c++ - 插入二叉树

c++ - 笨拙的 DLL 导出部分

c++ - 动态大小的不可调整大小的数组