我有两节课:
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
的关键字),但我 not 想要将它作为参数传递给{{1}的构造函数}。相反,我想将直接引用传递给将始终有效的地图元素。
我想过传递一个迭代器,但它很可能在更新期间或在向Person
添加映射时失效。
我该怎么做?
答案 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"));
}
}