将map元素的引用作为参数传递

时间:2014-08-04 17:27:44

标签: c++ oop unordered-map

我有两节课:

class Container
{
    /* ... */

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

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

不要说类Container动态更改AllDetails的内容。在我的main函数中,我构造了一个ContainerPerson的对象。每个Person对象都有一个唯一的id(这是AllDetails的关键字),但我 not 想要将它作为参数传递给{{1}的构造函数}。相反,我想将直接引用传递给将始终有效的地图元素。

我想过传递一个迭代器,但它很可能在更新期间或在向Person添加映射时失效。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

试试这个:

#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"));
    }
}