传递对映射元素的引用作为参数

Passing reference to map element as argument

本文关键字:引用 参数 元素 映射      更新时间:2023-10-16

我有两个类:

class Container
{
    /* ... */
    // Type 'PersonDetails' is a struct.
    std::unordered_map<unsigned int, PersonDetails> AllDetails;
};

class Person
{
public:
    Person(THE_ARGUMENT);
};

不假设类Container动态地改变了AllDetails的内容。在我的main函数中,我构造了一个Container的对象和一个Person的对象。每个Person对象都有一个唯一的id(这是AllDetails的键),但我不想把它作为参数传递给Person的构造函数。相反,我想将直接引用传递给map的元素,该元素将始终有效。

我想传递一个迭代器,但它很可能在更新或添加映射到AllDetails时无效。

我该怎么做呢?

试试这个:

#include <map>
#include <vector>
#include <memory>
#include <string>
#include <cassert>
struct PersonDetails 
{
    PersonDetails()
        : Age(0)
    {}
    std::string Name;
    int Age;
};
class Container
{
    /* ... */
public:
    typedef std::map<unsigned int, PersonDetails> PersonDetailsMap;
    typedef PersonDetailsMap::value_type          PersonDetailsElement;
    PersonDetailsElement& GetDetails(unsigned int ID)
    {
        auto it = AllDetails.lower_bound(ID);
        if (it != AllDetails.end() && !AllDetails.key_comp()(ID, it->first))
            return *it;
        else
            return *AllDetails.insert(it, std::make_pair(ID, PersonDetails()));
    }
    // Type 'PersonDetails' is a struct.
    std::map<unsigned int, PersonDetails> AllDetails;
};
class Person
{
public:
    Container::PersonDetailsElement& Details;
    Person(Container::PersonDetailsElement& details)
        : Details(details)
    {}
};
int main()
{
    Container c;
    using namespace std;
    vector<shared_ptr<Person>> people;
    for (int i = 0; i < 10000; ++i)
    {
        people.push_back(make_shared<Person>(c.GetDetails(i)));
        people.back()->Details.second.Age = 10 + i;
        people.back()->Details.second.Name = string("Bob");
        assert(people.back()->Details.first == i);
        assert(c.AllDetails[i].Age == 10 + i);
        assert(c.AllDetails[i].Name == string("Bob"));
    }
}