传递对映射元素的引用作为参数
Passing reference to map element as argument
我有两个类:
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"));
}
}
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 具有常量引用参数的函数模板专用化
- C++:常量引用参数
- 字符串引用参数的效率C++
- 通过非常量引用参数修改常量引用参数
- 如何将指针变量作为引用参数传递?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 移动类的成员作为常量引用参数传递
- C++带有适用于左值和右值的引用参数的函数
- constexpr 函数的常量引用参数:gcc/msvc vs clang/icc
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 委托构造函数和引用参数
- 对 const 引用参数使用默认值会导致崩溃
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 将非左值作为常量引用参数传递.临时是在本地作用域还是在调用方作用域中创建的?
- 如何强制函数仅接受左值引用参数
- 模板引用参数推断失败C++
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 将unique_ptr作为引用参数或常量传递unique_ptr引用