gpt4 book ai didi

c++ - 在结构的嵌套映射上链接 operator[]

转载 作者:行者123 更新时间:2023-11-30 03:13:59 24 4
gpt4 key购买 nike

我有以下内容:

struct A { std::map<int, B> b; }
struct B { std::map<int, C> c; };
std::map<int, A> a;

我想用 for 循环中的值填充 a:

for(int i : ...)
for(int j : ...)
for(int k : ...)
a[i].b[j].c.emplace(k, <args to constructor of C>);

这是低效的吗? a[i]b[j] 调用中的 A 和 B 对象是否会就地构建?答案是否取决于 a[i]b[j] 导致插入与分配的频率?这可以使用 try_emplace 以更简洁的方式完成吗?

最佳答案

问题

Is this inefficient?

一点点。您可以在本地存储对 a[i]a[i].b[j] 的引用以避免多次调用。

for(int i : ...)
{
auto& aref = a[i;
for(int j : ...)
{
auto& bref = aref.b[j];
for(int k : ...)
{
bref.c.emplace(k, <args to constructor of C>);
}
}
}

问题

Will the A and B objects in the calls to a[i] and b[j] be constructed in-place?

是的。

来自 https://en.cppreference.com/w/cpp/container/map/operator_at :

Inserts value_type(key, T()) if the key does not exist.

问题

Does the answer depend on how often a[i] and b[j] result in an insert versus assign?

没有。

问题

Can this be done in a less-verbose manner using try_emplace?

我不清楚你在这里问什么。

关于c++ - 在结构的嵌套映射上链接 operator[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58276344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com